Check if there is parameter | Code: if [ -n "$1" ] && [ -n "$2" ] # note the quoted test strings then echo "Strings \"$1\" and \"$2\" are not null." else echo "Strings \"$1\" and \"$2\" are null." fialternatively:
Code: if [ $1 ] && [ $2 ] then echo "Strings \"$1\" and \"$2\" are not null." else echo "Strings \"$1\" and \"$2\" are null." FiPasted from <> |
Calc value | $(( $1 + $2 )) |
Last command exit code | $? ( 0 normal ) |
Date string | Datestring=`date "+%d%m%Y"` |
File output | Echo |
Find out if a folder is mounted | if mount|grep FOLDERNAME ; then echo "mounted" else echo "unmounted" fi |
Find out if a file exists | if [ -r FILEPATH ]; then echo "exists" else echo "not exists" fi |
UnHide a folder | chflags nohidden ~/Library |
Open with specific tool under terminal | open -a Finder /usr/bin/ |
Make alias to a folder |
|
: | Python 'pass' equivalence |
Replace char in string | #!/bin/ksh x=A_B_C_D # replace _ with a space x=$(echo $x|sed 's/_/ /g') echo $x
Pasted from <>
|
Replace char by sed | mystr=abc/e echo $mystr | sed "s/\//d/g" #replace '/' to 'd' |
: | What? |
mkdir -p | -p creates intermediate directories |
var=0 let "var+=1" | Add 1 to $var |
read -p "Press Enter to continue" | Pause and enter to continue |
array[0]="a" array[1]="b" | Array is zero based
|
${#array[@]} | Array size/length |
select item in "${items[@]}"; do echo item; break; done; | Selection with array |
dirs=(*/) | Store directories in current folder to array dirs |
files=(*.dylib) | Store all files with extension name of .dylib to array files |
if [ -n "$var_to_test" ]; then ... fi | Check $var_to_test is not null |
string='My string';
if [[ $string == *My* ]] then echo "It's there!" fi | If you prefer the regex approach: if [[ $string =~ .*My.* ]]
Check if string contains certain elements |
: | Colon Historically, Bourne shells did have neither true nor false as builtins. true was instead simply aliased to :, and false to something like let 0. Nowadays, the primary reasons for using : are for needing scripts to be portable to ancient versions of Bourne-derived shells. As a simple example, now-ancient versions of the Korn shell (ksh88) did not have a ! command (for negating the exit code). Thus if you want to portably (across Bourne-derived shells) check for failed execution of a command, you could use: if command; then :; else ... fi Note that if requires a non-empty then clause, and comments do not count as non-empty. As an aside on the insanity that is portable shell scripts: for maximum portability, using : is in fact safer than using true. Modern systems typically have a true binary which will be used as a fall-back, if the shell happens to not have this builtin. But in the worst case, neither builtin nor binary exist, and then attempting to execute true will result in a "command not found" error. This, in turn, typically also leads to an exit code != 0, exactly the opposite of what was intended!
|