--- Title: Bash Tips & Tricks date: 2018-11-11T16:01:15+01:00 Author: Olivier De Ram Draft: false Categories: - administration - development Tags: - bash - script Truncated: true --- Usefull bash tips & tricks ### Usefull CLI shortcuts: Shortcut | Description ------------- | ------------- Ctrl+a | Jump to the beginning of the command line. Ctrl+e | Jump to the end of the command line. Ctrl+u | Clear from the cursor to the beginning of the command line. Ctrl+k | Clear from the cursor to the end of the command line. Ctrl+Left Arrow | Jump to the beginning of the previous word on the command line. Ctrl+Right Arrow | Jump to the end of the next word on the command line. Ctrl+r | Search the history list of commands for a pattern. Esc + . | Copy the last word of the previous command on the current command line where the cursor is ### Redirect output: Command | result --- | --- `> file` | redirect stdout to overwrite a file `>> file` | redirect stdout to append to a file `2> file` | redirect stderr to overwrite a file `2> /dev/null` | discard stderr error messages by redirecting to /dev/null `&> file` _(OR `> file 2>&1`)_ | redirect stdout and stderr to overwrite the same file `&>>` _(OR `>> file 2>&1`)_ | redirect stdout and stderr to append to the same file ### Create a function: It's straightforward, use function to create a function, give it a usefull short name and put the statemants between curly brackets. Use $1 for the first argument, $2 for the second argument and so on... ``` bash function { } ``` For example the function logsearch which searches for the given string whitin all logfiles in the current directory: ``` bash function logsearch { zgrep $1 ./*log } ``` ### Short scripts: * Loop every file in path: ``` bash for F in /path/to/files/*; do echo "Files $F"; done ``` * Loop file line per line: ``` bash while read LINE; do echo $LINE; done < file.txt ```