Introduction To Unix Commands
Introduction To Unix Commands
This is a very brief introduction to some useful Unix commands, including examples of how to use each command. For more extensive information about any of these commands, use the man command as described below. Sources for more information appear at the end of this document.
Commands
cal cp find lpr mv rmdir cat date jobs ls ps set cd df kill man pwd vi chmod du less
and more
and lp
mkdir rm w
and who
cal
This command will print a calendar for a specified month and/or year. To show this month's calendar, enter: cal To show a twelve-month calendar for 2008, enter: cal 2008 To show a calendar for just the month of June 1970, enter: cal 6 1970
cat
This command outputs the contents of a text file. You can use it to read brief files or to concatenate files together. To append file1 onto the end of file2, enter: cat file1 >> file2
To view the contents of a file named myfile, enter: cat myfile Because cat displays text without pausing, its output may quickly scroll off your screen. Use the less command (described below) or an editor for reading longer text files. For more, see In Unix, how do I combine several text files into a single file?
cd
This command changes your current directory location. By default, your Unix login session begins in your home directory. To switch to a subdirectory (of the current directory) named myfiles, enter: cd myfiles To switch to a directory named /home/dvader/empire_docs, enter: cd /home/dvader/empire_docs To move to the parent directory of the current directory, enter: cd .. To move to the root directory, enter: cd / To return to your home directory, enter: cd
chmod
This command changes the permission information associated with a file. Every file (including directories, which Unix treats as files) on a Unix system is stored with records indicating who has permission to read, write, or execute the file, abbreviated as r, w, and x. These permissions are broken down for three categories of user: first, the owner of the file; second, a group with which both the user and the file may be associated; and third, all other users. These categories are abbreviated as u for owner (or user), g for group, and o for other.
To allow yourself to execute a file that you own named myfile, enter: chmod u+x myfile To allow anyone who has access to the directory in which myfile is stored to read or execute myfile, enter: chmod o+rx myfile You can view the permission settings of a file using the ls command, described below. Note: Be careful with the chmod command. If you tamper with the directory permissions of your home directory, for example, you could lock yourself out or allow others unrestricted access to your account and its contents. For more, see In Unix, how do I change the permissions for a file?
cp
This command copies a file, preserving the original and creating an identical copy. If you already have a file with the new name, cp will overwrite and destroy the duplicate. For this reason, it's safest to always add -i after the cp command, to force the system to ask for your approval before it destroys any files. The general syntax for cp is: cp -i oldfile newfile To copy a file named meeting1 in the directory /home/dvader/notes to your current directory, enter: cp -i /home/dvader/notes/meeting1 . The . (period) indicates the current directory as destination, and the -i ensures that if there is another file named meeting1 in the current directory, you will not overwrite it by accident. To copy a file named oldfile in the current directory to the new name newfile in the mystuff subdirectory of your home directory, enter: cp -i oldfile ~/mystuff/newfile The ~ character (tilde) is interpreted as the path of your home directory. Note: You must have permission to read a file in order to copy it.
date
The date command displays the current day, date, time, and year. To see this information, enter: date
df
This command reports file system disk usage (i.e., the amount of space taken up on mounted file systems). For each mounted file system, df reports the file system device, the number of blocks used, the number of blocks available, and the directory where the file system is mounted. To find out how much disk space is used on each file system, enter the following command: df If the df command is not configured to show blocks in kilobytes by default, you can issue the following command: df -k
du
This command reports disk usage (i.e., the amount of space taken up by a group of files). The du command descends all subdirectories from the directory in which you enter the command, reporting the size of their contents, and finally reporting a total size for all the files it finds. To find out how much disk space your files take up, switch to your home directory with the cd command, and enter: du The numbers reported are the sizes of the files; on different systems, these sizes will be in units of either 512 byte blocks or kilobytes. To learn which is the case, use the man command, described below. On most systems, du -k will give sizes in kilobytes.
find
The find command lists all of the files within a directory and its subdirectories that match a set of conditions. This command is most commonly used to find all of the files that have a certain name. To find all of the files named myfile.txt in your current directory and all of its subdirectories, enter: find . -name myfile.txt -print To look in your current directory and its subdirectories for all of the files that end in the extension .txt , enter: find . -name "*.txt" -print In these examples, the . (period) represents your current directory. It can be replaced by the full pathname of another directory to search. For instance, to search for files named myfile.txt in the directory /home/user/myusername and its subdirectories, enter: find /home/user/myusername/ -name myfile.txt -print On some systems, omitting the final / (slash) after the directory name can cause find to fail to return any results. As a shortcut for searching in your home directory, enter: find "$HOME/" -name myfile.txt -print For more, see In Unix, what is the find command, and how do I use it to search through directories for files?
jobs
This command reports any programs that you suspended and still have running or waiting in the background (if you had pressed Ctrl-z to suspend an editing session, for example). For a list of suspended jobs, enter: jobs Each job will be listed with a number; to resume a job, enter % (percent sign) followed by the number of the job. To restart job number two, for example, enter: %2
This command is only available in the csh, bash, tcsh, and ksh shells.
kill
Use this command as a last resort to destroy any jobs or programs that you suspended and are unable to restart. Use the jobs command to see a list of suspended jobs. To kill suspended job number three, for example, enter: kill %3 Now check the jobs command again. If the job has not been cancelled, harsher measures may be necessary. Enter: kill -9 %3
lpr and lp
These commands print a file on a printer connected to the computer network. The lpr command is used on BSD systems, and the lp command is used in System V. Both commands may be used on the UITS systems. To print a file named myfile on a printer named lp1 with lpr, enter: lpr -Plp1 myfile To print the same file to the same printer with lp, enter: lp -dlp1 myfile Note: Do not print to a printer whose name or location is unfamiliar to you. For more, see In Unix, how do I print files and list or remove print jobs?
ls
This command will list the files stored in a directory. To see a brief, multi-column list of the files in the current directory, enter: ls To also see "dot" files (configuration files that begin with a period, such as .login ), enter: ls -a To see the file permissions, owners, and sizes of all files, enter: ls -la If the listing is long and scrolls off your screen before you can read it, combine ls with the less utility, for example: ls -la | less For more, see In Unix, how do I list the files in a directory?
man
This command displays the manual page for a particular command. If you are unsure how to use a command or want to find out all its options, you might want to try using man to view the manual page. For example, to learn more about the ls command, enter: man ls To learn more about man, enter: man man If you are not sure of the exact command name, you can use man with the -k option to help you find the command you need. To see one line summaries of each reference page that contains the keyword you specify, enter: man -k keyword Replace keyword in the above example with the keyword which you want to reference. Also see In Unix, what is the man command, and how do I use it to read manual pages?
mkdir
This command will make a new subdirectory. To create a subdirectory named mystuff in the current directory, enter: mkdir mystuff To create a subdirectory named morestuff in the existing directory named /tmp, enter: mkdir /tmp/morestuff Note: To make a subdirectory in a particular directory, you must have permission to write to that directory.
mv
This command will move a file. You can use mv not only to change the directory location of a file, but also to rename files. Unlike the cp command, mv will not preserve the original file.
Note: As with the cp command, you should always use -i to make sure you do not overwrite an existing file. To rename a file named oldname in the current directory to the new name newname, enter: mv -i oldname newname To move a file named hw1 from a subdirectory named newhw to another subdirectory named oldhw (both subdirectories of the current directory), enter: mv -i newhw/hw1 oldhw If, in this last operation, you also wanted to give the file a new name, such as firsthw, you would enter: mv -i newhw/hw1 oldhw/firsthw
ps
The ps command displays information about programs (i.e., processes) that are currently running. Entered without arguments, it lists basic information about interactive processes you own. However, it also has many options for determining what processes to display, as well as the amount of information about each. Like lp and lpr, the options available differ between BSD and System V implementations. For example, to view detailed information about all running processes, in a BSD system, you would use ps with the following arguments: ps -alxww To display similar information in System V, use the arguments: ps -elf For more information about ps refer to the ps man page on your system. Also see In Unix, what do the output fields of the ps command mean?
pwd
This command reports the current directory path. Enter the command by itself: pwd For more, see In Unix, how do I determine my current working directory?
rm
This command will remove (destroy) a file. You should enter this command with the i option, so that you'll be asked to confirm each file deletion. To remove a file named junk, enter: rm -i junk Note: Using rm will remove a file permanently, so be sure you really want to delete a file before you use rm. To remove a non-empty subdirectory, rm accepts the -r option. On most systems this will prompt you to confirm the removal of each file. This behavior can be prevented by adding the -f option. To remove an entire subdirectory named oldstuff and all of its contents, enter: rm -rf oldstuff Note: Using this command will cause rm to descend into each subdirectory within the specified subdirectory and remove all files without prompting you. Use this command with caution, as it is very easy to accidently delete important files. As a precaution, use the ls command to list the files within the subdirectory you wish to remove. To browse through a subdirectory named oldstuff, enter: ls -R oldstuff | less
rmdir
This command will remove a subdirectory. To remove a subdirectory named oldstuff, enter: rmdir oldstuff Note: The directory you specify for removal must be empty. To clean it out, switch to the directory and use the ls and rm commands to inspect and delete files.
set
This command displays or changes various settings and options associated with your Unix session.
To see the status of all settings, enter the command without options: set If the output scrolls off your screen, combine set with less: set | less The syntax used for changing settings is different for the various kinds of Unix shells; see the man entries for set and the references listed at the end of this document for more information.
vi
This command starts the vi text editor. To edit a file named myfile in the current directory, enter: vi myfile The vi editor works fairly differently from other text editors. If you have not used it before, you should probably look at a tutorial, such as How do I use the vi text editor? Another helpful document for getting started with vi is A quick reference list of vi editor commands. The very least you need to know to start using vi is that in order to enter text, you need to switch the program from command mode to insert mode by pressing i . To navigate around the document with the cursor keys, you must switch back to command mode by pressing Esc. To execute any of the following commands, you must switch from command mode to ex mode by pressing : (the colon key): Enter w to save; wq to save and quit; q! to quit without saving.
w and who
The w and who commands are similar programs that list all users logged into the computer. If you use w, you also get a list of what they are doing. If you use who, you also get the IP numbers or computer names of the terminals they are using.
Also see:
In Unix, how do I remove files with names that contain strange characters, such as spaces, semicolons, and backslashes?
if you've transferred files to your Unix account from a PC or Macintosh with filenames containing what Unix considers to be meta-characters, they may cause problems. Metacharacters (including semicolons, spaces, backslashes, dollar signs, question marks, and asterisks) are characters that are interpreted under Unix as commands or instructions. Although these characters may not cause any trouble in other operating systems, their special Unix interpretations may cause problems when you try to delete them. Try the following suggestions for deleting these files:
Try the regular rm command and enclose your troublesome filename in quotes. This may solve the problem of deleting files with spaces in their name, for example: rm "File Name" You can also remove some other characters in this manner, for example: rm "filename;#" The quotes prevent the semicolon from being interpreted as a stacking command. (Since you can string commands together in Unix with semicolons, Unix will interpret a semicolon in a filename that way, unless you put it in quotes.) You can also try renaming the problem file, using quotes around your original filename, by entering: mv "filename;#" new_filename If this command successfully renames the file, you can then use the rm command to delete the file using the new name. If this does not work, insert a backslash ( \ ) before the meta-character in your filename. The backslash causes the character that follows to be interpreted literally. For example, to remove the file named my$project, enter: rm my\ $project To remove a file whose name begins with a dash ( - ) character, refer to the file with the following syntax: rm ./-filename Using the redundant ./ directory information prevents the dash from occurring at the beginning of the filename, and being interpreted as an option of the rm command. There are some characters that you cannot remove using any of the above methods, such as forward slashes, interpreted by Unix as directory separators. To remove a file with such meta-characters, you may have to FTP into the account containing the file from a separate account and enter the command: mdel You will be asked if you really wish to delete each file in the directory. Be sure to answer n (for no) for each file except the file containing the difficult character that you wish to delete. Delete that file by typing y (for yes) when prompted. Once you've deleted the intended file, you may press Ctrl-c to discontinue the mdel process. Use this approach cautiously to avoid deleting other files by mistake. Note: If you're using a graphical FTP client, remove these files the same way you remove any other file.
Some Emacs editors allow you to directly edit a directory, and this provides yet another way to remove a file with a troublesome name. Consult Emacs documentation for more information.
To safeguard your Unix account, you should change your password at least every six months. For more information on what constitutes a secure password, see Passwords and passphrases.
At IU, how do I change or synchronize my Network ID passphrase? At IU, if I forget my passphrase on a UITS shared central system, what should I do? In Unix, what is a symbolic link, and how do I create one?
A symbolic link, also termed a soft link, is a special kind of file that points to another file, much like a shortcut in Windows or a Macintosh alias. Unlike a hard link, a symbolic link does not contain the data in the target file. It simply points to another entry somewhere in the file system. This difference gives symbolic links certain qualities that hard links do not have, such as the ability to link to directories, or to files on remote computers networked through NFS. Also, when you delete a target file, symbolic links to that file become unusable, whereas hard links preserve the contents of the file. To create a symbolic link in Unix, at the Unix prompt, enter the following command: ln -s source_file myfile Replace source_file with the name of the existing file for which you want to create the symbolic link (this file can be any existing file or directory across the file systems). Replace myfile with the name of the symbolic link. The ln command then creates the symbolic link. After you've made the symbolic link, you can perform an
operation on or execute myfile, just as you could with the source_file. You can use normal file management commands (e.g., cp, rm) on the symbolic link. Note: If you delete the source file or move it to a different location, your symbolic file will not function properly. You should either delete or move it. If you try to use it for other purposes (e.g., if you try to edit or execute it), the system will send a "file nonexistent" message. To find out more about symbolic links, you can view the man pages for the ln command. To do this, at the Unix prompt, enter the following command: man ln
You can change file permissions with the chmod command. In Unix, file permissions, which establish who may have different types of access to a file, are specified by both access classes and access types. Access classes are groups of users, and each may be assigned specific access types. The access classes are "user", "group", "other", and "all". These refer, respectively, to the user who owns the file, a specific group of users, the other remaining users who are not in the group, and all three sets of users. Access types (read, write, and execute) determine what may be done with the file by each access class. There are two basic ways of using chmod to change file permissions:
Symbolic method
The first and probably easiest way is the relative (or symbolic) method, which lets you specify access classes and types with single letter abbreviations. A chmod command with this form of syntax consists of at least three parts from the following lists: Access Class u (user) g (group) o (other) a (all: u, g, and o) For example, to add permission for everyone to read a file in the current directory named myfile, at the Unix prompt, you would enter: chmod a+r myfile The a stands for "all", the + for "add", and the r for "read". Operator + (add access) - (remove access) Access Type r (read) w (write)
Note: This assumes that everyone already has access to the directory where myfile is located and its parent directories; that is, you must set the directory permissions separately. If you omit the access class, it's assumed to be all, so you could also enter the previous example as: chmod +r myfile You can also specify multiple classes and types with a single command. For example, to remove read and write permission for group and other users (leaving only yourself with read and write permission) on a file named myfile, you would enter: chmod go-rw myfile You can also specify that different permissions be added and removed in the same command. For example, to remove write permission and add execute for all users on myfile, you would enter: chmod a-w+x myfile In each of these examples, the access types that aren't specified are unchanged. The previous command, for example, doesn't change any existing settings specifying whether users besides yourself may have read ( r ) access to myfile. You could also use the exact form to explicitly state that group and other users' access is set only to read with the = operator: chmod go=r myfile The chmod command also operates on directories. For example, to remove write permission for other users on a subdirectory named mydir, you would enter: chmod o-w mydir To do the same for the current directory, you would enter: chmod o-w Be careful when setting the permissions of directories, particularly your home directory; you don't want to lock yourself out by removing your own access. Also, you must have execute permission on a directory to switch ( cd ) to it.
Absolute form
The other way to use the chmod command is the absolute form. In this case, you specify a set of three numbers that together determine all the access classes and types. Rather than
being able to change only particular attributes, you must specify the entire state of the file's permissions. The three numbers are specified in the order: user (or owner), group, other. Each number is the sum of values that specify read (4), write (2), and execute (1) access, with 0 (zero) meaning no access. For example, if you wanted to give yourself read, write, and execute permissions on myfile; give users in your group read and execute permissions; and give others only execute permission, the appropriate number would be calculated as (4+2+1) (4+0+1)(0+0+1) for the three digits 751. You would then enter the command as: chmod 751 myfile As another example, to give only yourself read, write, and execute permission on the current directory, you would calculate the digits as (4+2+1)(0+0+0)(0+0+0) for the sequence 700, and enter the command: chmod 700 If it seems clearer to you, you can also think of the three digit sequence as the sum of attributes you select from the following table: 400 read by owner 200 write by owner 100 execute by owner 040 read by group 020 write by group 010 execute by group 004 read by others 002 write by others 001 execute by others To create an access mode, sum all the accesses you wish to permit. For example, to give read privileges to all, and write and execute privileges to the owner only for a file, you would sum: 400+200+100+040+004 = 744. Then, at the Unix prompt, you would enter: chmod 744 myfile.ext Some other frequently used examples are: 777 anyone can do anything (read, write, or execute) 755 you can do anything; others can only read and execute 711 you can do anything; others can only execute 644 you can read and write; others can only read
You can use the ls command to list the files in any directory to which you have access. For a simple directory listing, at the Unix prompt, enter:
ls This command will list the names of all the files and directories in the current working directory.
You can limit the files that are described by using fragments of filenames and wildcards. Examples of this are:
ls hello ls hel* ls hell?
Lists files whose complete name is hello ; if hello is a directory, displays the contents of the hello directory. Lists all files in the directory that begin with the characters hel (e.g., files named hel , hello , and hello.officer ).
Lists files that begin with hell followed by one character, such as helli , hello , hell1 . The * represents any number of unknown characters, while ? represents only one unknown character. You can use * and ? anywhere in the filename fragment. If you would like to list files in another directory, use the ls command along with the path to the directory. For example, if you are in your home directory and want to list the contents of the /etc directory, enter: ls /etc This will list the contents of the /etc directory in columns.
Several options control the way in which the information you get is displayed. Options are used in this format: ls -option filename Neither the options nor the filename are required (you may use ls by itself to see all the files in a directory). You may have multiple options and multiple filenames on a line. The options available with ls are far too numerous to list here, but you can see them all in the online manual (man) pages. Some of the more helpful options for ls are:
a d F
Shows all files, including those beginning with . (a period). The dot is special in the Unix file system. Shows directory names, but not contents. Marks special files with symbols to indicate what they are: / for directories, @ for symbolic links, * for executable programs.
l R
Shows the rights to the file, the owner, the size in bytes, and the time of the last modification made to the file. (The l stands for "long".) Recursively lists subdirectories.
The options can be combined. To list all the files in a directory in the long format, with marks for the types of files, you would enter: ls -Flg
As with many other Unix commands, you can redirect the output from ls to a file, or pipe it to another command. If you want to save a list of the files in your directory to a file named foo, you would use the following command combination: ls > foo If you want to mail a list of the files in your directory to a user named tom, you would use the following combination: ls | Mail tom In Unix, what startup and termination files do the various shells use?
Although not a comprehensive list, the following should provide you with a basic understanding of what startup and shutdown files the various Unix shells use. Note: This information comes from the Unix FAQ, which is posted regularly to the Usenet newsgroups comp.unix.questions and comp.unix.shell. You can obtain it by FTP from rtfm.mit.edu in the /pub/usenet directory, and on the web at: http://www.faqs.org/faqs/unix-faq/faq/
csh
Some versions have systemwide .cshrc and .login files. Each version puts them in different places. Startup (in this order):
.cshrc .login
Upon termination:
.logout
(login
shells)
tcsh
Startup (in this order): Upon termination: Others: (login (saves history based on "$savehist") .cshdirs (saves directory stack)
.history
.cshrc
present)
.login
sh
Startup (in this order):
/etc/profile
Upon termination: Any command or script specified using the command: trap "command" 0
(login
shells)
.profile
(login shells)
ksh
Startup (in this order):
/etc/profile
Upon termination: Any command or script specified using the command: trap "command" 0
(login
shells)
.profile (login shells) $ENV (always, if it is set)
bash
Startup (in this order): Upon termination: (login Others: (readline initialization)
.inputrc
/etc/profile (login shells) .bash_logout .bash_profile (login shells) shells) .profile (login if no .bash_profile
zsh
Startup (in this order):
.zshenv (always, unless the -f .zprofile (login shells) .zshrc (interactive shells, unless .zlogin (login shells)
(login shells)
rc
(login shells) In Unix, where can I get information on differences between the various shells? For information about various Unix shells, see UNIX shell differences and how to change your shell. This text is a portion of the Unix FAQ, and contains information about the history of Unix shells, their differences, a comparison table of features, and instructions about how to change your current shell. In Unix, how do I undelete a file?
WSomeday, you are going to accidentally type something like rm *.foo , and find you just deleted * instead of *.foo . Consider it a rite of passage. Of course, your system administrator should be doing regular backups. Check with your sysadmin (usually username root) to see if a recent backup copy of your file is available. For details, see the Knowledge Base document At IU, who can recover files and email accidentally deleted from UITS central systems? If the file is not available, read on. For all intents and purposes, when you delete a file with the rm command, it is gone; the system totally forgets which blocks scattered around the disk comprised your file. Even worse, the blocks from the file you just deleted are going to be the first ones taken and scribbled upon when the system needs more disk space. However, it is theoretically possible (but quite difficult), if you shut down the system immediately after you used rm , to recover portions of the data. Note: Under no condition will UITS honor requests to shut down any of the central systems to retrieve lost files. Your first reaction when you've used the rm command by mistake may be to make a shell alias or a procedure which changes rm to move files into a trash bin rather than delete them. That way you can recover them if you make a mistake, and periodically clean out your trash bin. This, however, is generally accepted as a bad idea. You will become dependent upon this behavior of rm, and you will find yourself someday on a normal system where it won't work. Also, you will eventually find that dealing with the disk space and time involved in maintaining the trash bin is a hassle. It might be easier just to be a bit more careful with the rm command. For starters, you should look up the -i option to the rm command in your manual. If you are still undaunted, then here is a possible simple answer. You can make yourself a can command, which moves files into a trash-can directory. In csh and tcsh, you can place the following commands in the .cshrc file in your home directory:
#junk file(s) to the trashcan: alias can 'mv\!* ~/.trashcan' #irretrievably empty trash: alias mtcan 'rm -rf ~/.trashcan/ ;mkdir ~/.trashcan' #ensure trashcan exists: if ( ! -d ~/.trashcan ) mkdir ~/.trashcan To automatically empty the trash when you log out, you can put the following in the .logout file in your home directory: rm -rf ~/.trashcan/ ; mkdir ~/.trashcan/ Optionally, you can create shell scripts for the can and mtcan commands. For can, the shell script should consist of the following: #!/bin/ksh if [ ! -d ~/.trashcan ] #ensure trashcan exists then mkdir ~/.trashcan fi mv $* ~/.trashcan/ #junk file(s) to the trashcan For the mtcan command, create a shell script that consists of the following: #!/bin/ksh rm -rf ~/.trashcan #irretrievably empty trash mkdir ~/.trashcan #recreate trashcan directory Also, if you use tcsh, you can place set rmstar in your .cshrc or .tcshrc file. This will cause the shell to prompt you for confirmation if you enter rm * . Note: This information comes from the Unix FAQ, which is posted regularly to the Usenet newsgroups comp.unix.questions and comp.unix.shell. You can obtain it by FTP from rtfm.mit.edu in the /pub/usenet directory, and on the web at: http://www.faqs.org/faqs/unix-faq/faq/
hat books are available for Unix, and where can I find them? You can find hundreds of books on Unix, covering everything from general usage to highly specific administration tasks. A good place to start is O'Reilly & Associates, easily the most well-known and respected publisher of Unix-related books. Visit the O'Reilly & Associates web page at: http://www.oreilly.com/ However, O'Reilly by no means has a monopoly on quality Unix material. For information and reviews about other books, visit online booksellers such as Amazon.com and Barnes & Noble. In Unix, how do I get a printed copy of a manual page?
Note: In the examples below, replace command with the name of the Unix command for which you would like the man page, and printer with the name of the printer to which you are printing. In Unix, if you want to print a manual page to your local printer, at the prompt, enter: man command | col -bx | ansiprt If you do not have ansiprt on your system, see the Knowledge Base document In Unix, how do I print a file to my local printer?
If you are using a BSD system to send the manual page to a networked printer, at the prompt, enter: man command | lpr -Pprinter On System V systems, enter: man command | lp -dprinter
Several Unix dialects use the whereis command to find where programs, or executables, are stored in the file structure of the computer. To use it at the Unix prompt, enter: whereis command Replace command with the name of the executable for which you are looking. For example, if you are looking for the location of the lpr command, you would enter: whereis lpr The whereis command will return something like the following: lpr: /usr/ucb/lpr /usr/man/man1/lpr.1 In this example, the query asked about the lpr command, which spools jobs to printers. The operating system returned two answers, and thus two paths. The first path is the location of the lpr executable, and the second path is the location of the lpr manual page. To find the path the operating system uses to execute a command when you enter it on the command line, use the which command instead, for example: which lpr This command will output something like the following: /var/bsd/lpr This means that when you enter lpr at the command line, the system is really executing /var/bsd/lpr.
To set your default (preferred) editor on your Unix account, you must define the VISUAL and EDITOR environment variables. When you have done this, most Unix programs that use text editors (e.g., trn, tin, nn, and the alternate editor in Pine) will use the editor you have set.
The way to set these environment variables depends upon which Unix shell you use. If you use csh or tcsh, at the shell prompt, enter: setenv VISUAL editor setenv EDITOR editor Replace editor with the editor you want to use (e.g., Emacs, Pico, or vi). If you use sh, ksh, or bash, at the shell prompt, enter: VISUAL=editor; export VISUAL EDITOR=editor; export EDITOR Replace editor with the editor you want to use (e.g., Emacs, Pico, or vi). Note: You may want to include the full path to the editor (e.g., /usr/local/bin/emacs, /usr/local/bin/pico, or /bin/vi) instead of just the name of the editor. By following the commands above, you will set the default editor for the current computing session only. To make these changes permanent, you will need to place the appropriate commands described above in your .login or .cshrc files (for csh or tcsh users) or your .profile file (if you use sh, ksh, or bash).
In Unix, what is the find command, and how do I use it to search through directories for files?
To use the find command, at the Unix prompt, enter: find . -name "pattern" -print Replace "pattern" with a filename or matching expression, such as "*.txt" . (Leave the double quotes in.)
Options
The general form of the command is: find (starting directory) (matching criteria and actions) The find command will begin looking in the starting directory you specify and proceed to search through all accessible subdirectories. You may specify more than one starting directory for searching. You have several options for matching criteria:
-atime n -mtime n -size n -type c
File was accessed n days ago File was modified n days ago File is n blocks big (a block is 512 bytes) Specifies file type: f=plain text, d=directory
Specifies file system type: 4.2 or nfs The filename is nam The file's owner is usr The file's group owner is grp The file's access mode is p (where p is an integer)
You can use + (plus) and - (minus) modifiers with the atime, mtime, and size criteria to increase their usefulness, for example:
-mtime +7 -atime -2
Matches files modified more than seven days ago Matches files accessed less than two days ago
-size +100 Matches files larger than 100 blocks (50KB) By default, multiple options are joined by "and". You may specify "or" with the -o flag and the use of grouped parentheses. To match all files modified more than 7 days ago and accessed more than 30 days ago, use: \( -mtime +7 -o -atime +30 \) You may specify "not" with an exclamation point. To match all files ending in .txt except the file notme.txt, use: \! -name notme.txt -name \*.txt You can specify the following actions for the list of files that the find command locates:
-print -exec cmd -ok cmd -mount -xdev -prune
Display pathnames of matching files. Execute command cmd on a file. Prompt before executing the command cmd on a file. (System V) Restrict to file system of starting directory. (BSD) Restrict to file system of starting directory. (BSD) Don't descend into subdirectories.
Executed commands must end with \; (a backslash and semi-colon) and may use {} (curly braces) as a placeholder for each file that the find command locates. For example, for a long listing of each file found, use: -exec ls -l {} \;
Matching criteria and actions may appear in any order and are evaluated from left to right.
Full examples
To find and report all C language source code files starting at the current directory, enter: find . -name \*.c -print To report all files starting in the directories /mydir1 and /mydir2 larger than 2000 blocks (about 1000KB) and that have not been accessed in over 30 days, enter: find /mydir1 /mydir2 -size +2000 -atime +30 -print To remove (with prompting) all files starting in the /mydir directory that have not been accessed in over 100 days, enter: find /mydir -atime +100 -ok rm {} \; To show a long listing starting in /mydir of files not modified in over 20 days or not accessed in over 40 days, enter: find /mydir \(-mtime +20 -o -atime +40\) -exec ls -l {} \; To list and remove all regular files named core starting in the directory /prog that are larger than 500KB, enter: find /prog -type f -size +1000 -print -name core -exec rm {} \; Note: On some systems, the name of the starting directory must end with a / (slash), or the find command will return nothing. Thus, the starting directory in the previous example would be designated as /prog/, with a trailing slash. On other systems, a trailing slash does not affect the command. A trailing slash is never needed when searching in / (the root directory), . (the current directory), or .. (the parent directory).
For more information, consult the Unix manual page by entering at the Unix prompt: man find Some of the above information came from Essential System Administration, Aeleen Frisch (O'Reilly & Associates, Inc., 1991).
Following are some options for online Unix tutorials for all user levels: http://unixhelp.ed.ac.uk/ http://www.math.utah.edu/lab/unix/unix-tutorial.html http://linux.2038bug.com/rute-home.html IT Training & Education offers a Unix fundamentals self-study course. If you have an IU Network ID, you can take the course via the web or on CD-ROM. For more, see Selfstudy training.
Note: Pine is not available on any central UITS systems. UITS does not support the use of Pine at Indiana University. Note: The software discussed here is no longer in common use at Indiana University, and UITS may no longer be able to verify the document's accuracy. The UITS Support Center may no longer have the manuals and other materials required to support this software adequately. You can access Unix commands from Pine either by exiting to the Unix shell or by piping to Unix commands from within Pine. When you exit to the Unix shell, you leave the Pine environment altogether and enter commands at the Unix command line prompt. When you use Pine's Pipe to Unix command, you send commands and receive output from the Unix shell while still in Pine.
In Unix, how can I split large files into a number of smaller files?
To split large files into smaller files in Unix, use the split command. At the Unix prompt, enter: split [options] filename prefix Replace filename with the name of the large file you wish to split. Replace prefix with the name you wish to give the small output files. You can exclude [options], or replace it with either of the following: -l linenumber -b bytes If you use the -l (a lowercase L) option, replace linenumber with the number of lines you'd like in each of the smaller files (the default is 1,000). If you use the -b option, replace bytes with the number of bytes you'd like in each of the smaller files. The split command will give each output file it creates the name prefix with an extension tacked to the end that indicates its order. By default, the split command adds aa to the first output file, proceeding through the alphabet to zz for subsequent files. If you do not specify a prefix, most systems use x .
Examples
In this simple example, assume myfile is 3,000 lines long: split myfile This will output three 1000-line files: xaa, xab, and xac.
Working on the same file, this next example is more complex: split -l 500 myfile segment This will output six 500-line files: segmentaa, segmentab, segmentac, segmentad, segmentae, and segmentaf.
Finally, assume myfile is a 160KB file: split -b 40k myfile segment This will output four 40KB files: segmentaa, segmentab, segmentac, and segmentad.
For more information, consult the man page for the split command. At the Unix prompt, enter: man split
You may also wish to investigate the csplit command, which splits files based on context. For more information, see the man page for the csplit command. At the Unix prompt, enter:
man csplit In Unix, how do I combine several text files into a single file?
In Unix, to combine several text files into a single file, use the cat command: cat file1 file2 file3 > newfile Replace file1, file2, and file3 with the names of the files you wish to combine, in the order you want them to appear in the combined document. Replace newfile with a name for your newly combined single file. If you want to add one or more files to an existing document, use the format: cat file1 file2 file3 >> destfile This command will add file1, file2, and file3 (in that order) to the end of destfile. Note: If you use > instead of >>, you will overwrite destfile rather than add to it.
On this page:
Introduction
You can use the chsh command to change your login shell. The instructions for using chsh vary among Unix implementations (see below). In all cases, changes do not take effect until the next time you log in. Executing the chsh command will not change the shell you are currently running. To find out which shell you're currently using, at the Unix prompt, enter: echo $SHELL
Shells on IU systems
Note: On the Libra Cluster at IU, the chsh command resets the login shell temporarily on the local node, but is overwritten the next time the user information files are globally distributed from the cluster management server node. For information on how to
permanently change your login shell on Libra, see On Libra, how do I change my login shell and password? The following shells are available on all central Unix systems at IUB: /bin/sh /bin/csh /bin/ksh /usr/local/bin/tcsh /usr/local/bin/bash
On computers running Linux, at the Unix prompt, enter: chsh -s newshell Replace newshell with the full pathname of the shell you want to use. Enter your password when prompted, and the system will change your shell. To see a list of the available shells, at the Unix prompt, enter: chsh -l
On computers running Solaris, at the Unix prompt, enter: chsh newshell Replace newshell with the full pathname of the shell you want to use. To see a list of the available shells, at the Unix prompt, enter: chsh
On HP-UX machines, at the Unix prompt, enter: chsh username newshell Replace username with your username, and newshell with the full pathname of the shell you wish to use. For example, if dvader wanted to change to bash, he would enter: chsh dvader /usr/local/bin/bash
On AIX, to list the available shells, at the Unix prompt, enter: chsh The system will then ask you if you really want to change your shell. If you press y and then Enter, you will be prompted to enter the full path of the new preferred shell. For example, to change to bash, enter: /usr/local/bin/bash
On computers running Tru64 Unix, at the Unix prompt, enter: chsh You'll then see something similar to the following: Old shell: /bin/csh New shell:
The old shell listed is the one currently running. To leave your shell unchanged, press Enter. To change shells, enter the full pathname of the shell you wish to use. For example, to change to bash from csh, at the "New shell:" prompt, enter: /usr/local/bin/bash
Other updates
Once you've changed your shell, you may wish to update your shell customization files if you have changed them for your old shell. The names of these files will depend on which shell you have chosen. For more information about what customization files your shell uses, see In Unix, what startup and termination files do the various shells use?
This is document afsk in domain all. Last modified on February 22, 2008.
An extension of the Bourne shell with several features adapted from the C shell; the POSIX shell is based on the Korn shell A revision of the C shell with substantially expanded capabilities; the default shell in modern BSD implementations, including Mac OS X/Darwin
sh
An extension of the Bourne shell, but with unique features; part of the GNU project and the default shell for Linux
For more information, see In Unix, where can I get information on differences between the various shells? You may find out what options you have for your login shell (i.e., your default shell) by looking at the file /etc/shells. Most shells double as interpreted programming languages. To automate tasks, you may write scripts containing built-in shell and Unix commands. When you execute a script, the shell interprets these commands just as if you had entered them from the commandline prompt. Compared to compiled programs, shell scripts are slow, but easy to write and debug. Note: In general, shells of the Bourne shell class are better for scripting than those derived from the C shell. To Unix, the shell is nothing more than another program. For this reason, any program can be designated a login shell in /etc/shells. For example, some Emacs users pride themselves on never needing a traditional shell prompt.
From Pine, how do I exit to the Unix shell without quitting the program?
If you have Pine suspension enabled, you may exit to the Unix shell prompt by pressing Ctrl-z . To return to Pine, at the Unix prompt, enter fg . If you don't have suspension enabled, when you press Ctrl-z , you will instead see the following error:
"[Pine suspension not enabled - see help text]" To enable suspension, follow these instructions: 1. At the Pine Main Menu, press s for Setup and then c for Config. 2. In the Setup Configuration menu, find the option "enable-suspend". Press x to activate Pine suspension. 3. Press e and then y to exit the Setup Configuration menu and save your changes. Note: If you would like Pine to create a subshell instead of exiting to its parent shell, in the Setup Configuration menu, also activate the option "use-subshell-for-suspend". With this option enabled, instead of entering fg to return to Pine, enter exit .
Also see:
In Pine, how do I access Unix commands? Unix job control command list
The following table lists the basic Unix job control commands: Command Explanation
& Ctrl-z jobs
Example
% long_cmd & [Ctrl-z] Stopped % jobs [1] - Stopped vi [2] - big_job & % fg %1 % fg %?ls % bg [2] big_job &
Run the command in the background Stop the foreground process List background processes Refers to the background number n Refers to the background job containing str Restart a stopped background process
Bring a background process to the foreground % fg %1 Kill a process Suspend an rlogin or ssh session
% kill %2 host2>~[Ctrl-z] Stopped host1> Stopped host2>
~~ Ctrl-z
This table is adapted from Essential System Administration, by Aeleen Frisch, copyright 1995, O'Reilly & Associates, Inc. Note: For security reasons, rlogin is not available on UITS computers at Indiana University.
To run the count program, which will display the process identification number of the job, enter: count & To check the status of your job, enter: ps You can bring a background process to the foreground by entering: fg If you have more than one job suspended in the background, enter: fg %# Replace # with the job number, as shown in the first column of the output of the jobs command.
You can kill a background process by entering: kill PID Replace PID with the process ID of the job. If that fails, enter the following: kill -KILL PID To determine a job's PID, enter: jobs -l If you are using sh, ksh, bash, or zsh, you may prevent background processes from sending error messages to the terminal. Redirect the output to /dev/null using the following syntax: count 2> /dev/null &
Batch jobs Changing a job's priority and running a job in the background
Batch jobs
For more information about the at and batch commands, see In Unix, what are at and batch, and how do I use them to submit non-interactive job requests? For information about using LoadLeveler on the Libra Cluster at Indiana University, see Using LoadLeveler on Libra at IU. For information about using LoadLeveler on Big Red at IU, see Getting started on Big Red. For information about using PBS on Quarry, see: http://rc.uits.iu.edu/hps/research/quarry/PBSguide.shtml
nice a.out & When the job is complete, you will see something like the following: [1] Done ls (csh/tcsh) For more information on the nice command, see the manual (man) page, which you can access by entering: man nice For more information on how to work with background processes, see the man page for your shell (e.g., csh, tcsh, ksh, bash).
Once you have the process ID, enter: kill <process ID> Replace <process ID> with the process ID. If it still will not terminate, try entering: kill -9 <process ID> Note: Other scheduling programs, such as NQS and LoadLeveler, work differently and are not controlled by the same methods. For more information, see the appropriate man pages.
In Unix, what are at and batch, and how do I use them to submit non-interactive job requests?
Note: Currently, you cannot access the at and batch commands on any UITS central systems. However, LoadLeveler (available on Big Red and the Libra Cluster) and TORQUE (available on Quarry) are more robust options that provide the same services. For more about LoadLeveler, see Getting started on Big Red and Using LoadLeveler on Libra at IU. For more about TORQUE, see What is TORQUE? In Unix, the at and batch commands allow you to schedule non-interactive tasks that execute, respectively, at a specified time or as soon as system resources permit. Once a job is completed, the system sends you mail messages containing the job's output and errors, if any. Unlike crontab, at and batch are generally used for jobs that are meant to run only once.
Syntax
To submit a job with the at command, first enter: at runtime Replace runtime with the date and time you want to execute the job. See "Setting the job execution time" below for more information. Once you have pressed Enter or Return, you may see a > or at> prompt. However, there may be no prompt at all. In any case, enter the command(s) and/or executable(s) that you would like to execute. Once you have finished, press Ctrld (or whatever your EOT character is). The system should report that the job has been submitted. The syntax for the batch command is identical except that you do not set an execution time.
Time:
Enter a one- or two-digit number (0-23) to indicate the start of an hour on a 24-hour clock (e.g., 13 is 13:00 or 1:00pm). To schedule the job to occur at a time other than the start of the hour, add minutes (00-59), optionally separated from the hour by a colon (e.g., 1334 or 13:34). You may follow the number with an am or pm to indicate the specific time on a 12-hour clock (e.g., 1:34pm or 0134pm). Finally, you may also use the words now, noon, and midnight to indicate the current time, 12:00pm, and 12:00am, respectively. If the time you indicate is later than the current time and you haven't specified a date, the job will execute the same day; otherwise, it will execute the next day. If you wish, you can schedule the job to execute on a specific date. You may use keywords, such as today, tomorrow, or one of the days of the week. The job will then execute at the soonest possible date that meets the requirements. You also may enter a fully qualified date, such as November 9, 2009 . The year is optional and you may also use abbreviations. As long as the date is unambiguous, your job request will probably succeed.
Date:
Increment: You also can specify the execution time by indicating how far in the future it should be, relative to the current time. To do this, enter a plus sign ( + ) followed by a number and then one of the following keywords: minutes, hours, days, months, or years. For example, assuming the current time is 12:00pm, the increment of +2 weeks would set the execution time at noon on a day two weeks hence. These elements can be combined, as in the following examples: at tuesday +2 hours This would schedule the job for the following Tuesday at a time two hours later than the current time. at 9am February 2 In this case, the execution time will be 9:00 in the morning on the second day of next February. at 1334 +3 months This job will run at 1:34pm on a date exactly three months from when you used the at command.
Options
-f script -l
Reads the commands to be executed from the file script instead of from standard input Lists the jobs you have queued; works only with at, but jobs submitted with batch will also be listed with this command (On some systems, this option has been replaced by a separate command, atq.) Sends you email notifying you the job has finished Cancels the job whose ID is job-number; works only with at, but jobs submitted with batch can also be removed (On some systems, this option has been replaced with a separate command, atrm.)
-m -r jobnumber
Examples
at noon tar -cf /users/dvader dvader.tar Ctrl-d In this example, the user submitted a job that will run at noon the same day if submitted in the morning, or noon the next day if submitted in the afternoon. When the task is performed, a tarball of the /users/dvader directory will be created. batch -f /home/hsolo/script1 In this case, rather than entering the commands into standard input, the user submitted a batch command for a job that will execute the script /home/hsolo/script1. at -m 0530 November 9, 2009 /users/chewie/hb28.script Ctrl-d At 5:30am on November 9, 2009 the script hb28.script will run. A mail message indicating that the script has been executed will be sent to the user who submitted the job. at -r skywalker.887664428.b Here, the user has deleted the job skywalker.887664428.b. For more information, consult the following man pages: at cron crontab
To use NCFTP, at the Unix prompt, enter: ncftp host Replace host with the name of the site to which you wish to connect. To connect to a site that requires a username and password, enter: ncftp -u host For a complete listing of NCFTP's features, at the Unix prompt, enter: man ncftp At Indiana University, Libra does not have NCFTP installed, but it is available on most other Unix computers at IU. Instead of a command-line FTP program, you can use a desktop client like Transmit for Mac OS or Mac OS X, or Hummingbird FTP (part of the Communications Software package on IUware at IU) for Windows. You can also use most web browsers; Mozilla's Firefox and SeaMonkey are both good options. Desktop clients and browsers are both much easier to use than command-line based FTP programs and allow you to transfer items directly to your hard disk. To access an FTP site via a web browser (and some FTP clients), use a URL such as: ftp://ftp.mozilla.org You can also download many files via anonymous FTP from web sites. Obtaining files via the web is usually easier than FTP and rarely involves usernames and passwords.
images are present in a web page by pressing * (the asterisk). If you already know an image's URL, you won't have to do this. To start Lynx, at the command line prompt, enter: lynx If you have a specific URL in mind, you can append it, as in the following example: lynx http://uits.iu.edu/ When you view a web page with Lynx, it consists of plain text, usually embedded with highlighted links to various other web pages. Using Lynx, you can navigate the web with just your arrow keys. The up and down arrow keys will move you from link to link on the page. The right arrow key will select a link and call up the page to which it points. The left arrow key will take you back to the page you were previously viewing. Note: Even if you see several links side by side on the same line, you still need to use the up and down arrow keys to move between them. Following is a list of some common Lynx commands:
For help and other Lynx information, press ? (the question mark). To scan through a long web page one screen at a time, use the Spacebar. Lynx has a bookmarks file; you can consider this a personal address book for sites on the web. To save the location of the page you're viewing, press a , and then d . To view your bookmarks file, press v . To see the document at a specific URL at any time, press g , and then enter the full URL. For example, to connect to the Yahoo web index, you would press g and then enter: http://www.yahoo.com/ To see the URL of the page you're viewing, press = (the equal sign). Then press = (the equal sign) again or the left arrow key to go back to the page. To abort your connection to a slow or unresponsive link, press: Ctrl-g To see the HTML source of the page you're looking at, press \ (the backslash). Then press \ (the backslash) again to re-display the plain text version.
For more information about Lynx, visit the Lynx Developers page. To download Lynx for most operating systems, visit the current release page.
To download a Lynx ported to the Mac OS X Installer system, visit the GNU Mac OS X Public Archive. Note: Lynx is also a short name of LynxOS, a Unix-like operating system produced by LynuxWorks. For more information, consult comp.os.lynx newsgroup or visit the LynuxWorks corporate web page.
To save the file on your Unix account, choose the first option to save it to disk. To save the file on your local computer, you can use the "print to screen" option in conjunction with the log or capture file function of the communications program you are using, as described below: 1. 2. 3. 4. In Lynx, to begin the printing process, press p . Highlight the "print to screen" option, but don't press Enter. In your communications program, start screen capture or logging. In Lynx, making sure that the "print to screen" option is still selected, press Enter. 5. When the printout is done, turn off screen capture or logging. The file should now be on your local computer.
If you want to download a text file for which there is a link on the current page, select the link and press d . Choose the option to save the file to the local disk, unless your local computer is running a program that can handle Kermit or Zmodem transfer. The "save to local disk" option will save the file to the account you are logged into. Or, if you can use the Kermit or Zmodem options, these will save the file to the computer you are using at the time. If the file you are downloading has HTML in it, the HTML will appear in the copy that is downloaded rather than being rendered.
In Mac OS, when I'm logged into a remote computer, how do I log or capture to a file everything that scrolls by my screen?
Note: For information on capturing in Mac OS X, see In Mac OS X, when I'm logged into a remote computer, how do I log or capture to a file everything that scrolls by my screen?
In Mac OS, being able to capture or log what scrolls by your screen when you're connected to a remote host depends on the software you're using. What follows are instructions for a few popular Macintosh programs.
ZTerm
To capture what scrolls by your screen using ZTerm: 1. From the File menu, select Start Capture... . 2. In the dialog box that appears, enter a filename. This file will store the captured text. 3. To stop the capture, from the File menu, select Stop Capture.
open host_name Replace host_name with the name of the computer to which you wish to connect. While authenticating to a host, if you accidentally press Enter at the Username: prompt, enter: user You will then be prompted for your username.
Also see:
Switch to ASCII mode. ASCII mode is the default mode; use it for transferring text files. Switch to binary mode. Use to transfer binary files, including files ending in .zip, .tar, .Z, and .gz, executable programs, and graphics files. Close the connection to the remote computer and exit FTP. Change the directory on the remote computer. Close the connection to the remote computer. Delete files from the remote computer. List the files in the current directory on the remote computer. Copy a file from the remote computer to the local computer.
(or
hash
Displays a # on the screen for every block of bytes transferred. A block is 1024 bytes in some cases, 2048 in others, but is between 1024 and 4096 in most cases. Check FTP's online help for the number represented in the FTP program you are using. (or Lists or provides help on the use of FTP commands. Change the directory on the local computer. Show the current directory (present working directory) on the local computer. This command is not available in all FTP versions. On Unix systems, try !pwd if lpwd doesn't work. Delete multiple files on the remote computer. Copy multiple files from the remote computer to the local computer. Create a directory on the remote host. Copy multiple files from the local computer to the remote computer. Open a connection to a remote computer. Turn on (or turn off) file transfer prompting. Often used to turn off prompting when using mdel, mput, or mget so that you are not required to confirm the transfer of each file before it is transferred. Copy a file from the local computer to the remote computer. Show the current directory (present working directory) on the remote computer. Remove a directory on the remote host (the directory usually has to be empty). Log into the remote computer to which you are currently connected. FTP will ask for a login name and possibly a password. In Unix, exit to the shell prompt, where you can enter commands. Enter exit to get back to FTP. If you follow ! with a command (e.g., !pwd), FTP will execute the command without dropping you to the Unix prompt.
If you use csh or tcsh, create a file called .logout. If you use bash, create a file called .bash_logout. In the file, put the commands you wish to have executed upon logging out. Use this feature with care. If your .logout file is lengthy or contains errors and you leave a public terminal before verifying that the file is done executing, an unscrupulous user could gain access to your account by interrupting its execution. Note: This function is distinct from cron, which can perform actions at particular dates and times while you are logged out.