Introduction
Shell scripting makes life more comfortable. The command sequences of Linux can be combined in one shell script and be executed automatically without wasting any time. For example, if you would like to rename 9,999,999 files and put them into different directories during one week, clicking the mouse will be devastating. By shell scripting, all you need is to run one command in a loop. After that, you can have a vacation and enjoy coffee in the next seven days.
Suppose we have known at least a little bit about Linux. What is a Linux shell? Shell is an command language interpreter that executes commands. The most commonly used shells are SH (Bourne SHell) and Bash (Bourne again shell), released in 1989. Bash is not a perfect scripting language, but it is very useful. Life is short, get rid of the mouse.
Shell Scripting Basics
Here are some examples and templates of the shell scripting to take care of the files and directories.
1 | reading the content of file1 and the output is written to file2 (instead of being displayed on screen) |
File Handling Primer
Note that “{” with a hashtag '#" will be a bug for Markdown editor. In the following code, a space is added before the hash. Please delete the space when running the code.
Example 1: delete, replace, grep…
1 | !/bin/bash |
Example 2: array, loop…
1 |
|
Run a Shell Script
Set the execute permission on your script:
1 | chmod u+x yourname.sh |
Enjoy it.
Advanced Shell Script
Remove all files/directories except for one file
1 | remove files except 'file.txt' |
In zsh, you must enable extendedglob
1 | setopt extendedglob && rm -- ^file.txt |