Bashing some more Commands
- In strings.sh
- If variable names contain things other than letters, it is best to include them in brackets.
- echo $10
- Will really echo -n $1; echo 0
- some string operators
- ${varname:-word}
- if varname is defined, return it, otherwise return word.
- echo ${undefined:-not defined}
- echo ${undefined:-$0}
- This is used to return a default value for a variable.
- ${varname:=word}
- If varname is defined return it, otherwise set it to word and return that
- ${varname:?message}
- If varname exists return it, otherwise print an error message and abort.
- ${varname:offset:length}
- Substring of varname from offset for length characters.
- If length is omitted, go to the end of the string
- Special case for $@
- return length parameters starting at offset
- There are others, but these will do.
- He gives a nice example in the book.
- Write a script that takes a file name and an optional number
- The file contains a number of lines in the format number word
- Display the top n lines of the file.
- Look at howmany.sh
- Patterns and pattern matching.
- Primitive, much better tools are available.
- ${varname#pattern}
- Find the shortest pattern at the beginning of the value in varname and return the rest of the string.
- ${varname##pattern}
- Find the longest pattern at the beginning of the value in varname and return the rest of the string.
- ${varname%pattern}
- Find the shortest pattern at the end of the value in varname and return the rest of the string.
- ${varname%%pattern}
- Find the longest pattern at the end of the value in varname and return the rest of the string.
- He gives the example outifle=${filename%.pcx}.jpg
- The length of a string is ${#varname}
- Saving the output of a command: command substitution
- val=`ls`