Differences

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

Link to this comparison view

Next revision
Previous revision
linux:shell [2008/09/08 20:27]
cyril created
linux:shell [2024/04/22 00:07] (current)
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 ''find'', with ''{}'' being the file name:
 +<code bash>
 +find . -type f -exec <command> {} \;
 +find -iname "<pattern>" -exec <command> {} \;
 +</code>
 +
 +Manual solution:
 <code bash> <code bash>
 #!/bin/sh #!/bin/sh
Line 28: 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.1220905649.txt.gz ยท Last modified: 2013/09/19 16:42 (external edit)
CC Attribution-Share Alike 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0