Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
linux:shell [2024/04/19 09:37]
cyril
linux:shell [2024/04/22 00:07] (current)
cyril [Misc]
Line 10: Line 10:
 </code> </code>
  
-==== Iterate over a list as a string ====+===== Iterate over a list as a string =====
  
-If you have to define it as a string, ''sh'' will work, and for ''zsh'' you have to execute before ''setopts shwordsplit'':+Different options:
 <code bash> <code bash>
-setopts shwordsplit+# option 1, without variable 
 +for x in a b c; do echo $x; done 
 + 
 +# option 2, with string
 list="a b c" list="a b c"
-for x in $list; do echo $x; done +for x in $list; do echo $x; done         # only works with sh and bash 
-</code>+for x in ${=list}; do echo $x; done      # only works with zsh 
 +for x in $(echo $list}; do echo $x; done # works with any shell
  
-However if you canit is better to define arrays: +# option 3with an array
-<code bash>+
 list=(a b c) list=(a b c)
 for x in $list; do echo $x; done for x in $list; do echo $x; done
Line 59: Line 62:
  
 search_dir "." search_dir "."
 +</code>
 +
 +===== Misc =====
 +
 +  * **Default value for variable**: <code bash>
 +${<variable>:-<default-value>}
 +</code>
 +  * **Get directory of current script** (for instance in order to run a script that is stored in the same directory, or in a known relative path):<code bash>
 +BASEDIR=$(dirname "$0")
 +</code>
 +  * **echo to stderr**, just redirect the output:<code bash>
 +echo "foo" 1>&2
 +</code>
 +  * **Convert dash-time to ISO** (2024-04-21_15-50-30 to 2024-04-21T15:50:30, for instance to use it as input for ''date''): <code bash>
 +sed -r "s/([0-9]{4})-([0-9]{2})-([0-9]{2})_([0-9]{2})-([0-9]{2})-([0-9]{2})/\1-\2\-3T\4:\5:\6/"
 +</code>
 +  * **Get target name of symbolic link**:<code bash>
 +readlink <symbolic-link>
 +</code>
 +  * **Execute command**:<code bash>
 +var=`cat file`
 +var=$(cat file)
 +</code>
 +  * **Evaluate mathematical expression** (''zsh'' also supports floating-point operations):<code bash>
 +echo $((2*3))
 +</code>
 +  * **time with redirected output** (also works for groups of commands):<code bash>
 +time (cat file1 > file2)
 +time (cat file1 > /dev/null; sync)
 +</code>
 +  * **Check number of arguments and print usage:**<code bash>
 +if [[ $# -lt 2 ]]; then
 +        echo "Usage: foo.sh <arg1> <arg2>" 1>&2
 +        exit 1
 +fi
 +</code>
 +  * Load command output as a file:<code>
 +diff <(grep x file1) <(grep y file2)
 </code> </code>
linux/shell.1713519445.txt.gz · Last modified: 2024/04/19 09:37 by cyril
CC Attribution-Share Alike 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0