Variable
Single Value
Basic variable usage
Creating variables:
set var_name value
read my_nameUsing variables:
echo $HOME
echo {$WORD}s
echo "$foo $bar"Compare datetime
To easily compare date and time in fish, we remove / and : to make them become numbers, and then use test to compare.
function check_time --argument-names now # now is in format HH:MM
set now (echo "$now" | tr -d :)
if test "$now" -lt 0600
echo 'You should be sleeping now!'
else if test "$now" -lt 1200
echo 'Good morning!'
else if test "$now" -lt 1800
echo 'Good day!'
else
echo 'Good night!'
end
endSave command output
Save the output of a command in a variable and use it later (possibly several times to avoid running the command every time):
ps -ef | read --null ps_output
printf '%s' $ps_output | sed -nE 's#pattern#\1#p'Array
Basic array usage
Creating an array:
set fruits banana orange melonFish uses base 1 for accessing values in a list.
echo $fruits[1] # => bananaUse negative index to access from the end.
echo $fruits[-1] # => melonGet a slice with the .. syntax (left/right defaults: 1..-1)
echo $fruits[..-2] # => banana orangeEscape and expand arrays
Print an array with every element quoted with ' (useful if we need to expand it inside " for another command):
echo "'$(string join "' '" $fruits)'" # => 'banana' 'orange' 'melon'If outside double quotes, the same can achieved with:
echo \'$fruits\' # => 'banana' 'orange' 'melon'The same syntax can be used to expand multiple arguments:
set options --arg=$fruits # => --arg=banana --arg=orange --arg=melonIntegrate arrays with commands
Output of commands can be splitted on newlines if using command substitution:
set lines (cmd)To pipe an array to a command, make each element be in one line:
string join \n $fruits | cmd
printf '%s\n' $fruits | cmdWith this we can, for example, sort the elements of an array:
set fruits (string join \n $fruits | sort)Avoid cat
To avoid running cat and creating a new process just to print the contents of a file, use fish's builtin read instead.
# Instead of
set lines (cat input_file)
# Do
set lines (read --null <input_file)Special variables
| Bash | Fish | Description |
|---|---|---|
$0 | status filename | Filename of current script. |
$* $@ $1 | $argv | Script or function arguments. |
$# | count $argv | Number of arguments. |
$? | $status | Return code of last command. |
$! | $last_pid | PID of last program run in background. |
$$ | $fish_pid | Current fish PID. |
$- | status is-interactive status is-login | Check shell interactivity. |
Load environment file
Considering .env an environment file (with KEY=VALUE tuples), one can export those variables in fish using:
export (xargs -L 1 <.env)Or a more complex solution like:
export (grep -E '^[^#;].+=.*' .env | xargs -L 1)