School of Computing. Dublin City University.
Shell gives you a quick and powerful way of having a programmable User Interface, where you can quickly write short programs to automate repetitive tasks.
I have had a changing collection of my own personal shell scripts moving with me from place to place and machine to machine since the 1980s. It is I think the only technology that I have found useful for that entire period.
Shell program can have any extension (typically no extension). Edit a file, put some UNIX commands in it, perhaps strung together with some logic:
if condition then rm f1 else rm f2 fiMake it executable:
$ chmod +x fileMake sure it is in the PATH and just run it:
$ file $ file &
Advantage: Don't have to worry about chmod or PATH.$ sh prog
Some people like to end scripts with an extension:
Advantage: Can easily see what the file is from a directory listing.$ prog.sh $ sh prog.sh
I don't use either of these. I make scripts executable, put them in PATH, and use no extensions. Then I just type:
Remember pipes and redirection on command line.
sed explained later. Here it does a "search and replace" operation on text.
cat file | grep -i "http:.*dcu.ie" | sed -e "s|COMPAPP|computing|g" | sed -e "s|compapp|computing|g" | sort -u
UNIX separates "ordinary output" (standard output, stdout, 1>, >) from "error output" (standard error, stderr, 2>) prog > output 2> errors
> /dev/null to get rid of some unwanted output e.g. error/warning messages from compilation/search (redirects it into a non-existent file)The null device exists on Windows too.
To redirect script output to a file, from command line: script > file To redirect script output to a file from within the script, put this at start of script: exec > file Then run: script
ls (gives multi-column output) ls > file (gives single-column output) ls | prog (gives single-column output)You can detect if output is going to terminal, file or pipe, and adjust output accordingly.
if [ -t 1 ] then echo stdout else echo pipe or file fi
prog prog | cat prog > file
$* all arguments to the Shell program $1 1st argument, etc. $@ like $* except deals differently with arguments with spaces and wildcards $0 name of prog $# no. of args # comment shift shift args leftwards this is useful if you want to remove some of the first args, then "shift" a couple of times, and then do "for i in $*" with the remaining args e.g. grep (switches) (string) file1 ... filen exit exit the Shell script exit 0 exit with a return code that other progs can query $? return code of last prog executed e.g. quiet grep: grep > /dev/null and then check $? though grep may have -q (quiet) option anyway
# test if 1st argument = "0" if test "$1" = "0" then echo "yes" else echo "no - first argument is $1" fi