Operating System‎ > ‎Linux‎ > ‎Linux Shell Script‎ > ‎

05. Shell Variables and Command Line Arguments (Part 1)


Overview
  • The shell has special variables that it uses to store data about the process that it’s running.
  • The shell allows the programmer to access these variables through their names
  • The name of these variables is a punctuation character so it may seem hard to read, but it is chosen to be that way so it would not interfere with user defined variable names
  • Topics
    • General purpose variables that store data of the current process
    • Variables for command line arguments
    • Command line options

Shell Variable ?

  • As you’ve seen before, the ? variable stores the exit status of the most recently run command or process
  • In a script, immediately after a command runs, you can check $? for the command’s exit status.
  • In Unix / Linux standard, an exit status of 0 means success (everything runs without error). An exit status of non-zero means there is an error.
  • An exit status number has a range between 0 and 255
  • The script itself is a process when it runs, so at the end of your script, you can also write exit 0 to indicate that everything runs fine from beginning to end. 
  • In your script you can check for a certain error condition and if there is error, you can write exit N where N is non-zero.
  • When the shell runs the script and gets to an exit N command, it terminates the script and returns with a status value of N, which is stored in the ? variable

Shell Variable $

  • The $ variable stores the PID, or Process ID, of the current command or process
  • Each process that runs has a unique ID assigned to it, called the PID.
  • Within the script, you can see its process ID  by accessing $$
  • On the command line, you can use the ps utility to see the process ID of your current process
  • One common use of the $ variable is to create unique temporary files while the script is running
  • Example:
    • awk  ‘{print $2}’  $file  >  file$$
    • take field 2 of the file in $file and send it to a temporary file called file3982 (assuming the PID of the script is 3982)
  • The advantage of creating unique temporary files is when 2 people are running the same script, they don’t overwrite each other’s temporary files

Shell Variable !

  • The ! variable holds the PID of the last process that is put in the background
  • Example
    • [mytest@abc ~]$ echo PID of the shell is $$
      • PID of the shell is 20366
    • [mytest@abc ~]$ sleep 25 &
      • [1] 20399
    • [mytest@abc ~]$ echo PID of the sleep process is $!
      • PID of the sleep process is 20399
  [ sleep is a utility that pauses execution for a certain amount of time. The numeric argument is for the number of seconds.
In the example above, execution will pause for 25 seconds but the whole sleep process runs in the background. Recall that when the shell puts a process in the background, it gives you the PID of the process. ]


Comments