Shell Scripting
Notes on shell scripting, as well as some zsh- and bash-specific stuff.
Notes
zsh has two representations for array variables like PATH and CDPATH, of which the lower case variant is an actual array
~
is a special character. Therefore, if you use it in a string variable and then try to do something with it,~
will be evaluated literally, and not expanded to the value of $HOME. So use $HOME in these cases insteadFunctions can be declared with/without
function
keyword and parensmy_function ()
,function my_function
, etc
To pass arguments to a function, just use spaces
my_function "hello" "world"
If passing variables, sometimes it's good practice to put them in quotes in case the variables have spaces in them
The
export
keyword is only necessary when sub-processes need access to the variableSo if you don't use
export
, when you execute programs they won't have access to the variable. But the resulting shell will
To do string transformation on strings in zsh upon expansion, use expansion flags
To rename the current directory:
mv ../current_dir ../new_dir_name
ormv ../{test,test2}
(uses brace expansion for brevity)Assigning test/[[]] results to a variable (tl;dr: there's not a great way to do this). This would be nice for code readability
Can't assign variable to command exit status directly
But can get around it using
$?
:(grep foo bar.txt); var1=$?
macOS has a weird quirk where filenames with a
:
show a/
for them insteadCan get around this if you need to by using this guy instead:
꞉
-- it's a different character but looks pretty similar
For conditionals, 0 is truthy and 1 is falsey
For multline string usage, use HereDoc
For stripping trailing characters, use parameter expansion
%
:${var%/}
, (stripping/
)
Links
Last updated