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
Last revision Both sides next revision
linux:shell [2024/04/19 09:30]
cyril better solution for recursive exec
linux:shell [2024/04/21 14:03]
cyril [Misc]
Line 1: Line 1:
 ====== Shell ====== ====== Shell ======
 +
 +===== Block comment =====
 +
 +With "END" being just an example of any random string that must not appear in the commented section:
 +<code bash>
 +: << 'END'
 +sleep 1
 +END
 +</code>
 +
 +===== Iterate over a list as a string =====
 +
 +Different options:
 +<code bash>
 +# option 1, without variable
 +for x in a b c; do echo $x; done
 +
 +# option 2, with string
 +list="a b c"
 +for x in $list; do echo $x; done         # only works with sh and bash
 +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
 +
 +# option 3, with an array
 +list=(a b c)
 +for x in $list; do echo $x; done
 +</code>
  
 ===== Do something recursively on all files ===== ===== Do something recursively on all files =====
  
-Use bash, with ''{}'' being the file name:+Use ''find'', with ''{}'' being the file name:
 <code bash> <code bash>
 find . -type f -exec <command> {} \; find . -type f -exec <command> {} \;
Line 35: 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> </code>
linux/shell.txt ยท Last modified: 2024/04/22 00:07 by cyril
CC Attribution-Share Alike 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0