Unix / Linux – Shell Input/Output Redirections ”; Previous Next In this chapter, we will discuss in detail about the Shell input/output redirections. Most Unix system commands take input from your terminal and send the resulting output back to your terminal. A command normally reads its input from the standard input, which happens to be your terminal by default. Similarly, a command normally writes its output to standard output, which is again your terminal by default. Output Redirection The output from a command normally intended for standard output can be easily diverted to a file instead. This capability is known as output redirection. If the notation > file is appended to any command that normally writes its output to standard output, the output of that command will be written to file instead of your terminal. Check the following who command which redirects the complete output of the command in the users file. $ who > users Notice that no output appears at the terminal. This is because the output has been redirected from the default standard output device (the terminal) into the specified file. You can check the users file for the complete content − $ cat users oko tty01 Sep 12 07:30 ai tty15 Sep 12 13:32 ruth tty21 Sep 12 10:10 pat tty24 Sep 12 13:07 steve tty25 Sep 12 13:03 $ If a command has its output redirected to a file and the file already contains some data, that data will be lost. Consider the following example − $ echo line 1 > users $ cat users line 1 $ You can use >> operator to append the output in an existing file as follows − $ echo line 2 >> users $ cat users line 1 line 2 $ Input Redirection Just as the output of a command can be redirected to a file, so can the input of a command be redirected from a file. As the greater-than character > is used for output redirection, the less-than character < is used to redirect the input of a command. The commands that normally take their input from the standard input can have their input redirected from a file in this manner. For example, to count the number of lines in the file users generated above, you can execute the command as follows − $ wc -l users 2 users $ Upon execution, you will receive the following output. You can count the number of lines in the file by redirecting the standard input of the wc command from the file users − $ wc -l < users 2 $ Note that there is a difference in the output produced by the two forms of the wc command. In the first case, the name of the file users is listed with the line count; in the second case, it is not. In the first case, wc knows that it is reading its input from the file users. In the second case, it only knows that it is reading its input from standard input so it does not display file name. Here Document A here document is used to redirect input into an interactive shell script or program. We can run an interactive program within a shell script without user action by supplying the required input for the interactive program, or interactive shell script. The general form for a here document is − command << delimiter document delimiter Here the shell interprets the << operator as an instruction to read input until it finds a line containing the specified delimiter. All the input lines up to the line containing the delimiter are then fed into the standard input of the command. The delimiter tells the shell that the here document has completed. Without it, the shell continues to read the input forever. The delimiter must be a single word that does not contain spaces or tabs. Following is the input to the command wc -l to count the total number of lines − $wc -l << EOF This is a simple lookup program for good (and bad) restaurants in Cape Town. EOF 3 $ You can use the here document to print multiple lines using your script as follows − Live Demo #!/bin/sh cat << EOF This is a simple lookup program for good (and bad) restaurants in Cape Town. EOF Upon execution, you will receive the following result − This is a simple lookup program for good (and bad) restaurants in Cape Town. The following script runs a session with the vi text editor and saves the input in the file test.txt. #!/bin/sh filename=test.txt vi $filename <<EndOfCommands i This file was created automatically from a shell script ^[ ZZ EndOfCommands If you run this script with vim acting as vi, then you will likely see output like the following − $ sh test.sh Vim: Warning: Input is not from a terminal $ After running the script, you should see the following added to the file test.txt − $ cat test.txt This file was created automatically from a shell script $ Discard the output Sometimes you will need to execute a command, but you don”t want the output displayed on the screen. In such cases, you can discard the output by redirecting it to the file /dev/null − $ command > /dev/null Here command is the name of the command you want to execute. The file /dev/null is a special file that automatically discards all its input. To discard both output of a command and its error output, use standard redirection to redirect STDERR to STDOUT − $ command > /dev/null 2>&1 Here 2 represents STDERR and 1 represents STDOUT. You can display a message on to STDERR by redirecting STDOUT into STDERR as follows − $ echo message 1>&2 Redirection Commands Following is a complete list of commands which you can use for redirection − Sr.No. Command & Description 1 pgm > file Output of pgm is redirected to file 2 pgm <
Category: unix
Unix / Linux – File System Basics ”; Previous Next A file system is a logical collection of files on a partition or disk. A partition is a container for information and can span an entire hard drive if desired. Your hard drive can have various partitions which usually contain only one file system, such as one file system housing the /file system or another containing the /home file system. One file system per partition allows for the logical maintenance and management of differing file systems. Everything in Unix is considered to be a file, including physical devices such as DVD-ROMs, USB devices, and floppy drives. Directory Structure Unix uses a hierarchical file system structure, much like an upside-down tree, with root (/) at the base of the file system and all other directories spreading from there. A Unix filesystem is a collection of files and directories that has the following properties − It has a root directory (/) that contains other files and directories. Each file or directory is uniquely identified by its name, the directory in which it resides, and a unique identifier, typically called an inode. By convention, the root directory has an inode number of 2 and the lost+found directory has an inode number of 3. Inode numbers 0 and 1 are not used. File inode numbers can be seen by specifying the -i option to ls command. It is self-contained. There are no dependencies between one filesystem and another. The directories have specific purposes and generally hold the same types of information for easily locating files. Following are the directories that exist on the major versions of Unix − Sr.No. Directory & Description 1 / This is the root directory which should contain only the directories needed at the top level of the file structure 2 /bin This is where the executable files are located. These files are available to all users 3 /dev These are device drivers 4 /etc Supervisor directory commands, configuration files, disk configuration files, valid user lists, groups, ethernet, hosts, where to send critical messages 5 /lib Contains shared library files and sometimes other kernel-related files 6 /boot Contains files for booting the system 7 /home Contains the home directory for users and other accounts 8 /mnt Used to mount other temporary file systems, such as cdrom and floppy for the CD-ROM drive and floppy diskette drive, respectively 9 /proc Contains all processes marked as a file by process number or other information that is dynamic to the system 10 /tmp Holds temporary files used between system boots 11 /usr Used for miscellaneous purposes, and can be used by many users. Includes administrative commands, shared files, library files, and others 12 /var Typically contains variable-length files such as log and print files and any other type of file that may contain a variable amount of data 13 /sbin Contains binary (executable) files, usually for system administration. For example, fdisk and ifconfig utlities 14 /kernel Contains kernel files Navigating the File System Now that you understand the basics of the file system, you can begin navigating to the files you need. The following commands are used to navigate the system − Sr.No. Command & Description 1 cat filename Displays a filename 2 cd dirname Moves you to the identified directory 3 cp file1 file2 Copies one file/directory to the specified location 4 file filename Identifies the file type (binary, text, etc) 5 find filename dir Finds a file/directory 6 head filename Shows the beginning of a file 7 less filename Browses through a file from the end or the beginning 8 ls dirname Shows the contents of the directory specified 9 mkdir dirname Creates the specified directory 10 more filename Browses through a file from the beginning to the end 11 mv file1 file2 Moves the location of, or renames a file/directory 12 pwd Shows the current directory the user is in 13 rm filename Removes a file 14 rmdir dirname Removes a directory 15 tail filename Shows the end of a file 16 touch filename Creates a blank file or modifies an existing file or its attributes 17 whereis filename Shows the location of a file 18 which filename Shows the location of a file if it is in your PATH You can use Manpage Help to check complete syntax for each command mentioned here. The df Command The first way to manage your partition space is with the df (disk free) command. The command df -k (disk free) displays the disk space usage in kilobytes, as shown below − $df -k Filesystem 1K-blocks Used Available Use% Mounted on /dev/vzfs 10485760 7836644 2649116 75% / /devices 0 0 0 0% /devices $ Some of the directories, such as /devices, shows 0 in the kbytes, used, and avail columns as well as 0% for capacity. These are special (or virtual) file systems, and although they reside on the disk under /, by themselves they do not consume disk space. The df -k output is generally the same on all Unix systems. Here”s what it usually includes − Sr.No. Column & Description 1 Filesystem The physical file system name 2 kbytes Total kilobytes of space available on the storage medium 3 used Total kilobytes of space used (by files) 4 avail Total kilobytes available for use 5 capacity Percentage of total space used by files 6 Mounted on What the file system is mounted on You can use the -h (human readable) option to display the output in a format that shows the size in easier-to-understand notation. The du Command The du (disk usage) command enables you to specify directories to show disk space usage on a particular directory. This command is helpful if you want to determine how much space a particular directory is taking. The following command displays number of blocks consumed by each directory. A single block may take either 512 Bytes or 1 Kilo Byte depending on your system. $du /etc 10 /etc/cron.d 126 /etc/default
Unix / Linux – Regular Expressions with SED ”; Previous Next In this chapter, we will discuss in detail about regular expressions with SED in Unix. A regular expression is a string that can be used to describe several sequences of characters. Regular expressions are used by several different Unix commands, including ed, sed, awk, grep, and to a more limited extent, vi. Here SED stands for stream editor. This stream-oriented editor was created exclusively for executing scripts. Thus, all the input you feed into it passes through and goes to STDOUT and it does not change the input file. Invoking sed Before we start, let us ensure we have a local copy of /etc/passwd text file to work with sed. As mentioned previously, sed can be invoked by sending data through a pipe to it as follows − $ cat /etc/passwd | sed Usage: sed [OPTION]… {script-other-script} [input-file]… -n, –quiet, –silent suppress automatic printing of pattern space -e script, –expression = script …………………………. The cat command dumps the contents of /etc/passwd to sed through the pipe into sed”s pattern space. The pattern space is the internal work buffer that sed uses for its operations. The sed General Syntax Following is the general syntax for sed − /pattern/action Here, pattern is a regular expression, and action is one of the commands given in the following table. If pattern is omitted, action is performed for every line as we have seen above. The slash character (/) that surrounds the pattern are required because they are used as delimiters. Sr.No. Range & Description 1 p Prints the line 2 d Deletes the line 3 s/pattern1/pattern2/ Substitutes the first occurrence of pattern1 with pattern2 Deleting All Lines with sed We will now understand how to delete all lines with sed. Invoke sed again; but the sed is now supposed to use the editing command delete line, denoted by the single letter d − $ cat /etc/passwd | sed ”d” $ Instead of invoking sed by sending a file to it through a pipe, the sed can be instructed to read the data from a file, as in the following example. The following command does exactly the same as in the previous example, without the cat command − $ sed -e ”d” /etc/passwd $ The sed Addresses The sed also supports addresses. Addresses are either particular locations in a file or a range where a particular editing command should be applied. When the sed encounters no addresses, it performs its operations on every line in the file. The following command adds a basic address to the sed command you”ve been using − $ cat /etc/passwd | sed ”1d” |more daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh $ Notice that the number 1 is added before the delete edit command. This instructs the sed to perform the editing command on the first line of the file. In this example, the sed will delete the first line of /etc/password and print the rest of the file. The sed Address Ranges We will now understand how to work with the sed address ranges. So what if you want to remove more than one line from a file? You can specify an address range with sed as follows − $ cat /etc/passwd | sed ”1, 5d” |more games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh $ The above command will be applied on all the lines starting from 1 through 5. This deletes the first five lines. Try out the following address ranges − Sr.No. Range & Description 1 ”4,10d” Lines starting from the 4th till the 10th are deleted 2 ”10,4d” Only 10th line is deleted, because the sed does not work in reverse direction 3 ”4,+5d” This matches line 4 in the file, deletes that line, continues to delete the next five lines, and then ceases its deletion and prints the rest 4 ”2,5!d” This deletes everything except starting from 2nd till 5th line 5 ”1~3d” This deletes the first line, steps over the next three lines, and then deletes the fourth line. Sed continues to apply this pattern until the end of the file. 6 ”2~2d” This tells sed to delete the second line, step over the next line, delete the next line, and repeat until the end of the file is reached 7 ”4,10p” Lines starting from 4th till 10th are printed 8 ”4,d” This generates the syntax error 9 ”,10d” This would also generate syntax error Note − While using the p action, you should use the -n option to avoid repetition of line printing. Check the difference in between the following two commands − $ cat /etc/passwd | sed -n ”1,3p” Check the above command without -n as follows − $ cat /etc/passwd | sed ”1,3p” The Substitution Command The substitution command, denoted by s, will substitute any string that you specify with any other string that you specify. To substitute one string with another, the sed needs to have the information on where the first string ends and the substitution string begins. For this, we proceed with bookending the two strings with the forward slash (/) character. The following command substitutes the first occurrence on a line of the string root with the string amrood. $ cat /etc/passwd | sed ”s/root/amrood/” amrood:x:0:0:root user:/root:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/sh …………………….. It is very important to note that sed substitutes only the first occurrence on a line. If the string root occurs more than once on a line only the first match will be replaced. For the sed to perform a global substitution, add the letter g to the end of the command as follows − $ cat /etc/passwd | sed ”s/root/amrood/g” amrood:x:0:0:amrood user:/amrood:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh ……………………… Substitution Flags There are a number of other useful flags that can be passed in addition to the g flag, and you can specify more than one at a time. Sr.No. Flag & Description 1 g Replaces all matches, not just the first match 2 NUMBER
Unix / Linux – System Performance ”; Previous Next In this chapter, we will discuss in detail about the system performance in Unix. We will introduce you to a few free tools that are available to monitor and manage performance on Unix systems. These tools also provide guidelines on how to diagnose and fix performance problems in the Unix environment. Unix has following major resource types that need to be monitored and tuned − CPU Memory Disk space Communications lines I/O Time Network Time Applications programs Performance Components The following table lists out five major components which take up the system time − Sr.No. Component & Description 1 User State CPU The actual amount of time the CPU spends running the users’ program in the user state. It includes the time spent executing library calls, but does not include the time spent in the kernel on its behalf 2 System State CPU This is the amount of time the CPU spends in the system state on behalf of this program. All I/O routines require kernel services. The programmer can affect this value by blocking I/O transfers 3 I/O Time and Network Time This is the amount of time spent moving data and servicing I/O requests 4 Virtual Memory Performance This includes context switching and swapping 5 Application Program Time spent running other programs – when the system is not servicing this application because another application currently has the CPU Performance Tools Unix provides following important tools to measure and fine tune Unix system performance − Sr.No. Command & Description 1 nice/renice Runs a program with modified scheduling priority 2 netstat Prints network connections, routing tables, interface statistics, masquerade connections, and multicast memberships 3 time Helps time a simple command or give resource usage 4 uptime This is System Load Average 5 ps Reports a snapshot of the current processes 6 vmstat Reports virtual memory statistics 7 gprof Displays call graph profile data 8 prof Facilitates Process Profiling 9 top Displays system tasks You can use Manpage Help to check complete syntax for each command mentioned here. Print Page Previous Next Advertisements ”;
Unix / Linux – Communication
Unix / Linux – Network Communication Utilities ”; Previous Next In this chapter, we will discuss in detail about network communication utilities in Unix. When you work in a distributed environment, you need to communicate with remote users and you also need to access remote Unix machines. There are several Unix utilities that help users compute in a networked, distributed environment. This chapter lists a few of them. The ping Utility The ping command sends an echo request to a host available on the network. Using this command, you can check if your remote host is responding well or not. The ping command is useful for the following − Tracking and isolating hardware and software problems. Determining the status of the network and various foreign hosts. Testing, measuring, and managing networks. Syntax Following is the simple syntax to use the ftp command − $ping hostname or ip-address The above command starts printing a response after every second. To come out of the command, you can terminate it by pressing CNTRL + C keys. Example Following is an example to check the availability of a host available on the network − $ping google.com PING google.com (74.125.67.100) 56(84) bytes of data. 64 bytes from 74.125.67.100: icmp_seq = 1 ttl = 54 time = 39.4 ms 64 bytes from 74.125.67.100: icmp_seq = 2 ttl = 54 time = 39.9 ms 64 bytes from 74.125.67.100: icmp_seq = 3 ttl = 54 time = 39.3 ms 64 bytes from 74.125.67.100: icmp_seq = 4 ttl = 54 time = 39.1 ms 64 bytes from 74.125.67.100: icmp_seq = 5 ttl = 54 time = 38.8 ms — google.com ping statistics — 22 packets transmitted, 22 received, 0% packet loss, time 21017ms rtt min/avg/max/mdev = 38.867/39.334/39.900/0.396 ms $ If a host does not exist, you will receive the following output − $ping giiiiiigle.com ping: unknown host giiiiigle.com $ The ftp Utility Here, ftp stands for File Transfer Protocol. This utility helps you upload and download your file from one computer to another computer. The ftp utility has its own set of Unix-like commands. These commands help you perform tasks such as − Connect and login to a remote host. Navigate directories. List directory contents. Put and get files. Transfer files as ascii, ebcdic or binary. Syntax Following is the simple syntax to use the ftp command − $ftp hostname or ip-address The above command would prompt you for the login ID and the password. Once you are authenticated, you can access the home directory of the login account and you would be able to perform various commands. The following tables lists out a few important commands − Sr.No. Command & Description 1 put filename Uploads filename from the local machine to the remote machine. 2 get filename Downloads filename from the remote machine to the local machine. 3 mput file list Uploads more than one file from the local machine to the remote machine. 4 mget file list Downloads more than one file from the remote machine to the local machine. 5 prompt off Turns the prompt off. By default, you will receive a prompt to upload or download files using mput or mget commands. 6 prompt on Turns the prompt on. 7 dir Lists all the files available in the current directory of the remote machine. 8 cd dirname Changes directory to dirname on the remote machine. 9 lcd dirname Changes directory to dirname on the local machine. 10 quit Helps logout from the current login. It should be noted that all the files would be downloaded or uploaded to or from the current directories. If you want to upload your files in a particular directory, you need to first change to that directory and then upload the required files. Example Following is the example to show the working of a few commands − $ftp amrood.com Connected to amrood.com. 220 amrood.com FTP server (Ver 4.9 Thu Sep 2 20:35:07 CDT 2009) Name (amrood.com:amrood): amrood 331 Password required for amrood. Password: 230 User amrood logged in. ftp> dir 200 PORT command successful. 150 Opening data connection for /bin/ls. total 1464 drwxr-sr-x 3 amrood group 1024 Mar 11 20:04 Mail drwxr-sr-x 2 amrood group 1536 Mar 3 18:07 Misc drwxr-sr-x 5 amrood group 512 Dec 7 10:59 OldStuff drwxr-sr-x 2 amrood group 1024 Mar 11 15:24 bin drwxr-sr-x 5 amrood group 3072 Mar 13 16:10 mpl -rw-r–r– 1 amrood group 209671 Mar 15 10:57 myfile.out drwxr-sr-x 3 amrood group 512 Jan 5 13:32 public drwxr-sr-x 3 amrood group 512 Feb 10 10:17 pvm3 226 Transfer complete. ftp> cd mpl 250 CWD command successful. ftp> dir 200 PORT command successful. 150 Opening data connection for /bin/ls. total 7320 -rw-r–r– 1 amrood group 1630 Aug 8 1994 dboard.f -rw-r—– 1 amrood group 4340 Jul 17 1994 vttest.c -rwxr-xr-x 1 amrood group 525574 Feb 15 11:52 wave_shift -rw-r–r– 1 amrood group 1648 Aug 5 1994 wide.list -rwxr-xr-x 1 amrood group 4019 Feb 14 16:26 fix.c 226 Transfer complete. ftp> get wave_shift 200 PORT command successful. 150 Opening data connection for wave_shift (525574 bytes). 226 Transfer complete. 528454 bytes received in 1.296 seconds (398.1 Kbytes/s) ftp> quit 221 Goodbye. $ The telnet Utility There are times when we are required to connect to a remote Unix machine and work on that machine remotely. Telnet is a utility that allows a computer user at one site to make a connection, login and then conduct work on a computer at another site. Once you login using Telnet, you can perform all the activities on your remotely connected machine. The following is an example of Telnet session − C:>telnet amrood.com Trying… Connected to amrood.com. Escape character is ”^]”. login: amrood amrood”s Password: ***************************************************** * * * * * WELCOME TO AMROOD.COM * * * * * ***************************************************** Last unsuccessful login: Fri Mar 3 12:01:09 IST 2009 Last login: Wed Mar 8 18:33:27 IST 2009 on pts/10 { do your work } $ logout Connection closed. C:> The finger Utility The finger command
Shell Scripting Tutorial ”; Previous Next A shell script is a computer program designed to be run by the Unix/Linux shell which could be one of the following: The Bourne Shell The C Shell The Korn Shell The GNU Bourne-Again Shell A shell is a command-line interpreter and typical operations performed by shell scripts include file manipulation, program execution, and printing text. Extended Shell Scripts Shell scripts have several required constructs that tell the shell environment what to do and when to do it. Of course, most scripts are more complex than the above one. The shell is, after all, a real programming language, complete with variables, control structures, and so forth. No matter how complicated a script gets, it is still just a list of commands executed sequentially. The following script uses the read command which takes the input from the keyboard and assigns it as the value of the variable PERSON and finally prints it on STDOUT. #!/bin/sh # Author : Zara Ali # Copyright (c) Tutorialspoint.com # Script follows here: echo “What is your name?” read PERSON echo “Hello, $PERSON” Here is a sample run of the script − $./test.sh What is your name? Zara Ali Hello, Zara Ali $ Subsequent part of this tutorial will cover Unix/Linux Shell Scripting in detail. Print Page Previous Next Advertisements ”;
Unix / Linux – What is Shells? ”; Previous Next A Shell provides you with an interface to the Unix system. It gathers input from you and executes programs based on that input. When a program finishes executing, it displays that program”s output. Shell is an environment in which we can run our commands, programs, and shell scripts. There are different flavors of a shell, just as there are different flavors of operating systems. Each flavor of shell has its own set of recognized commands and functions. Shell Prompt The prompt, $, which is called the command prompt, is issued by the shell. While the prompt is displayed, you can type a command. Shell reads your input after you press Enter. It determines the command you want executed by looking at the first word of your input. A word is an unbroken set of characters. Spaces and tabs separate words. Following is a simple example of the date command, which displays the current date and time − $date Thu Jun 25 08:30:19 MST 2009 You can customize your command prompt using the environment variable PS1 explained in the Environment tutorial. Shell Types In Unix, there are two major types of shells − Bourne shell − If you are using a Bourne-type shell, the $ character is the default prompt. C shell − If you are using a C-type shell, the % character is the default prompt. The Bourne Shell has the following subcategories − Bourne shell (sh) Korn shell (ksh) Bourne Again shell (bash) POSIX shell (sh) The different C-type shells follow − C shell (csh) TENEX/TOPS C shell (tcsh) The original Unix shell was written in the mid-1970s by Stephen R. Bourne while he was at the AT&T Bell Labs in New Jersey. Bourne shell was the first shell to appear on Unix systems, thus it is referred to as “the shell”. Bourne shell is usually installed as /bin/sh on most versions of Unix. For this reason, it is the shell of choice for writing scripts that can be used on different versions of Unix. In this chapter, we are going to cover most of the Shell concepts that are based on the Borne Shell. Shell Scripts The basic concept of a shell script is a list of commands, which are listed in the order of execution. A good shell script will have comments, preceded by # sign, describing the steps. There are conditional tests, such as value A is greater than value B, loops allowing us to go through massive amounts of data, files to read and store data, and variables to read and store data, and the script may include functions. We are going to write many scripts in the next sections. It would be a simple text file in which we would put all our commands and several other required constructs that tell the shell environment what to do and when to do it. Shell scripts and functions are both interpreted. This means they are not compiled. Example Script Assume we create a test.sh script. Note all the scripts would have the .sh extension. Before you add anything else to your script, you need to alert the system that a shell script is being started. This is done using the shebang construct. For example − #!/bin/sh This tells the system that the commands that follow are to be executed by the Bourne shell. It”s called a shebang because the # symbol is called a hash, and the ! symbol is called a bang. To create a script containing these commands, you put the shebang line first and then add the commands − #!/bin/bash pwd ls Shell Comments You can put your comments in your script as follows − #!/bin/bash # Author : Zara Ali # Copyright (c) Tutorialspoint.com # Script follows here: pwd ls Save the above content and make the script executable − $chmod +x test.sh The shell script is now ready to be executed − $./test.sh Upon execution, you will receive the following result − /home/amrood index.htm unix-basic_utilities.htm unix-directories.htm test.sh unix-communication.htm unix-environment.htm Note − To execute a program available in the current directory, use ./program_name Extended Shell Scripts Shell scripts have several required constructs that tell the shell environment what to do and when to do it. Of course, most scripts are more complex than the above one. The shell is, after all, a real programming language, complete with variables, control structures, and so forth. No matter how complicated a script gets, it is still just a list of commands executed sequentially. The following script uses the read command which takes the input from the keyboard and assigns it as the value of the variable PERSON and finally prints it on STDOUT. #!/bin/sh # Author : Zara Ali # Copyright (c) Tutorialspoint.com # Script follows here: echo “What is your name?” read PERSON echo “Hello, $PERSON” Here is a sample run of the script − $./test.sh What is your name? Zara Ali Hello, Zara Ali $ Print Page Previous Next Advertisements ”;
Unix / Linux – Shell Decision Making ”; Previous Next In this chapter, we will understand shell decision-making in Unix. While writing a shell script, there may be a situation when you need to adopt one path out of the given two paths. So you need to make use of conditional statements that allow your program to make correct decisions and perform the right actions. Unix Shell supports conditional statements which are used to perform different actions based on different conditions. We will now understand two decision-making statements here − The if…else statement The case…esac statement The if…else statements If else statements are useful decision-making statements which can be used to select an option from a given set of options. Unix Shell supports following forms of if…else statement − if…fi statement if…else…fi statement if…elif…else…fi statement Most of the if statements check relations using relational operators discussed in the previous chapter. The case…esac Statement You can use multiple if…elif statements to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable. Unix Shell supports case…esac statement which handles exactly this situation, and it does so more efficiently than repeated if…elif statements. There is only one form of case…esac statement which has been described in detail here − case…esac statement The case…esac statement in the Unix shell is very similar to the switch…case statement we have in other programming languages like C or C++ and PERL, etc. Print Page Previous Next Advertisements ”;
Unix / Linux – Using Arrays
Unix / Linux – Using Shell Arrays ”; Previous Next In this chapter, we will discuss how to use shell arrays in Unix. A shell variable is capable enough to hold a single value. These variables are called scalar variables. Shell supports a different type of variable called an array variable. This can hold multiple values at the same time. Arrays provide a method of grouping a set of variables. Instead of creating a new name for each variable that is required, you can use a single array variable that stores all the other variables. All the naming rules discussed for Shell Variables would be applicable while naming arrays. Defining Array Values The difference between an array variable and a scalar variable can be explained as follows. Suppose you are trying to represent the names of various students as a set of variables. Each of the individual variables is a scalar variable as follows − NAME01=”Zara” NAME02=”Qadir” NAME03=”Mahnaz” NAME04=”Ayan” NAME05=”Daisy” We can use a single array to store all the above mentioned names. Following is the simplest method of creating an array variable. This helps assign a value to one of its indices. array_name[index]=value Here array_name is the name of the array, index is the index of the item in the array that you want to set, and value is the value you want to set for that item. As an example, the following commands − NAME[0]=”Zara” NAME[1]=”Qadir” NAME[2]=”Mahnaz” NAME[3]=”Ayan” NAME[4]=”Daisy” If you are using the ksh shell, here is the syntax of array initialization − set -A array_name value1 value2 … valuen If you are using the bash shell, here is the syntax of array initialization − array_name=(value1 … valuen) Accessing Array Values After you have set any array variable, you access it as follows − ${array_name[index]} Here array_name is the name of the array, and index is the index of the value to be accessed. Following is an example to understand the concept − Live Demo #!/bin/sh NAME[0]=”Zara” NAME[1]=”Qadir” NAME[2]=”Mahnaz” NAME[3]=”Ayan” NAME[4]=”Daisy” echo “First Index: ${NAME[0]}” echo “Second Index: ${NAME[1]}” The above example will generate the following result − $./test.sh First Index: Zara Second Index: Qadir You can access all the items in an array in one of the following ways − ${array_name[*]} ${array_name[@]} Here array_name is the name of the array you are interested in. Following example will help you understand the concept − Live Demo #!/bin/sh NAME[0]=”Zara” NAME[1]=”Qadir” NAME[2]=”Mahnaz” NAME[3]=”Ayan” NAME[4]=”Daisy” echo “First Method: ${NAME[*]}” echo “Second Method: ${NAME[@]}” The above example will generate the following result − $./test.sh First Method: Zara Qadir Mahnaz Ayan Daisy Second Method: Zara Qadir Mahnaz Ayan Daisy Print Page Previous Next Advertisements ”;
Unix / Linux – Manpage Help
Unix / Linux – Shell Manpage Help ”; Previous Next All the Unix commands come with a number of optional and mandatory options. It is very common to forget the complete syntax of these commands. Because no one can possibly remember every Unix command and all its options, we have online help available to mitigate this right from when Unix was at its development stage. Unix”s version of Help files are called man pages. If there is a command name and you are not sure how to use it, then Man Pages help you out with every step. Syntax Here is the simple command that helps you get the detail of any Unix command while working with the system − $man command Example Suppose there is a command that requires you to get help; assume that you want to know about pwd then you simply need to use the following command − $man pwd The above command helps you with the complete information about the pwd command. Try it yourself at your command prompt to get more detail. You can get complete detail on man command itself using the following command − $man man Man Page Sections Man pages are generally divided into sections, which generally vary by the man page author”s preference. Following table lists some common sections − Sr.No. Section & Description 1 NAME Name of the command 2 SYNOPSIS General usage parameters of the command 3 DESCRIPTION Describes what the command does 4 OPTIONS Describes all the arguments or options to the command 5 SEE ALSO Lists other commands that are directly related to the command in the man page or closely resemble its functionality 6 BUGS Explains any known issues or bugs that exist with the command or its output 7 EXAMPLES Common usage examples that give the reader an idea of how the command can be used 8 AUTHORS The author of the man page/command To sum it up, man pages are a vital resource and the first avenue of research when you need information about commands or files in a Unix system. Useful Shell Commands The following link gives you a list of the most important and very frequently used Unix Shell commands. If you do not know how to use any command, then use man page to get complete detail about the command. Here is the list of Unix Shell – Useful Commands Print Page Previous Next Advertisements ”;