Top 10 bash skills to improve Linux Efficiency

Source: Internet
Author: User
Tags website server

Top 10 bash skills to improve Linux Efficiency

I like to delve into the bash environment. Many times, in bash programming, some problems are repeated over and over again. Every time I have to rethink how to solve these problems. One day I couldn't bear it, so I sat down and wrote a general function, put it into my. bashrc file, and deployed it on my computer.

I hope that my efforts to maximize the efficiency of the command line can also help other friends who like to use bash. My larger expectation is that this kind of behavior can lead to interaction among other friends-provide me with suggestions and better bash skills. Please leave a message to discuss it later, or leave a message in @ programmer's field of view.

Let's not talk about anything more. The following is my summary.

Tip 1: Use the command line to add text to the top of the file

Every time I search for the command again. The following describes how to use sed to add a row to the top of a file:

sed -i '1s/^/line to insert\n/' path/to/file/you/want/to/change.txt
Tip 2: Use command lines to insert multiple lines of text into the configuration file

This method is very simple and many people know how to insert multiple lines of text into a file using command lines (>. Here we use the "here document" syntax, which allows you to insert a paragraph into a File using a block text symbol. Generally, we use an EOF (meaning "End Of File "):

cat >> path/to/file/to/append-to.txt << "EOF"export PATH=$HOME/jdk1.8.0_31/bin:$PATHexport JAVA_HOME=$HOME/jdk1.8.0_31/EOF

All content between two "EOF" is added to the file.

Tip 3: Use command line recursion to search for and replace directory files globally

If you use Eclipse, ItelliJ, or other IDE, the powerful refactoring capabilities of these tools may make it easy to implement many things. However, I guess many times you do not have such integrated tools in your development environment.

How can I use the command line to Recursively search and replace a directory? Don't think about the Perl language. You can use find and sed. Thanks to the guidance provided by Stack Overflow:

# OSX versionfind . -type f -name '*.txt' -exec sed -i '' s/this/that/g {} +

After using it for a while, I wrote out a function and added it to. bashrc, as shown below:

function sr {    find . -type f -exec sed -i '' s/$1/$2/g {} +}

You can use it like this:

sr wrong_word correct_word
Tip 4: Use the command line to open a temporary file in vim and Dropbox

I used to like to use scratch facility in Emacs. Vim is often used to quickly create temporary files. The following two functions generate a random string using openssl as the file name:

function sc {  gvim ~/Dropbox/$(openssl rand -base64 10 | tr -dc 'a-zA-Z').txt}function scratch {  gvim ~/Dropbox/$(openssl rand -base64 10 | tr -dc 'a-zA-Z').txt}

In the command line window, enterscOrscratchA new gvim or macvim window will pop up, and a temporary file with a random file name will be loaded.

Tip 5: Use command lines to download files, including link redirection, HTTPS, and secure encryption.

Download a page and output it to the terminal. Follow the link to redirect and ignore security exceptions:

curl -Lks <some-url>

Download a link and follow the link to ignore security exceptions:

curl -OLks <some-url/to/a/file.tar.gz>

Many parameters are used here. You can read this simple curl document to learn about them.

Tip 6: Bashmarks

Haven't you used bashmarks in. bashrc? What are you waiting? It is really useful. It helps you maintain historical operations and jump back to your frequently used directory. The following is a script in my configuration file, but I think the above link provides you with more tips:

# USAGE:# s bookmarkname - saves the curr dir as bookmarkname# g bookmarkname - jumps to the that bookmark# g b[TAB] - tab completion is available# l - list all bookmarks# save current directory to bookmarkstouch ~/.sdirsfunction s {  cat ~/.sdirs | grep -v "export DIR_$1=" > ~/.sdirs1  mv ~/.sdirs1 ~/.sdirs  echo "export DIR_$1=$PWD" >> ~/.sdirs}# jump to bookmarkfunction g {  source ~/.sdirs  cd $(eval $(echo echo $(echo \$DIR_$1)))}# list bookmarks with dirnamfunction l {  source ~/.sdirs  env | grep "^DIR_" | cut -c5- | grep "^.*="}# list bookmarks without dirnamefunction _l {  source ~/.sdirs  env | grep "^DIR_" | cut -c5- | grep "^.*=" | cut -f1 -d "="}# completion command for gfunction _gcomp {    local curw    COMPREPLY=()    curw=${COMP_WORDS[COMP_CWORD]}    COMPREPLY=($(compgen -W '`_l`' -- $curw))    return 0}# bind completion command for g to _gcompcomplete -F _gcomp g
Tip 7: extract a column from formatted output (the most frequently used awk Technique)

I use it almost every day. True. There are often some outputs. I only need the second or third columns. The following command can do this:

#Sample output of git status -s command:$ git status -sM .bashrc?? .vim/bundle/extempore/# Remove status code from git status and just get the file names$ git status -s | awk '{print $2}'.bashrc.vim/bundle/extempore/

Why don't we write a function that we can use at any time?

function col {  awk -v col=$1 '{print $col}'}

This makes it very easy to extract columns. For example, you don't want the first column? Simple:

$ git status -s | col 2.bashrc.vim/bundle/extempore/
Tip 8: Ignore the first x words

I'm fascinated by xargs, and I feel like a knife. However, sometimes you need to adjust the result obtained by using it, and you may need to obtain some values. For example, you want to remove some information in the following file image:

function skip {    n=$(($1 + 1))    cut -d' ' -f$n-}

Here is how to use it:

  • Use docker images to get the following output:
$ docker imagesREPOSITORY                   TAG         IMAGE ID            CREATED             VIRTUAL SIZE<none>                       <none>      65a9e3ef7171        3 weeks ago         1.592 GB<none>                       <none>      7c01ca6c30f2        3 weeks ago         11.1 MB<none>                       <none>      9518620e6a0e        3 weeks ago         7.426 MB<none>                       <none>      430707ee7fe8        3 weeks ago         7.426 MBboot2docker/boot2docker      latest      1dbd7ebffe31        3 weeks ago         1.592 GBspaceghost/tinycore-x86_64   5.4         f47686df00df        7 weeks ago         11.1 MBdurdn/bithub                 latest      df1e39df8dbf        8 weeks ago         100.9 MB<none>                       <none>      c5e6cf38d985        8 weeks ago         100.9 MBnginx                        latest      e426f6ef897e        12 weeks ago        100.2 MBzoobab/tinycore-x64          latest      8cdd417ec611        8 months ago        7.426 MBscratch                      latest      511136ea3c5a        20 months ago       0 B
  • Using the above function, you can obtain all IDs:
$ docker images | col 3IMAGE65a9e3ef71717c01ca6c30f29518620e6a0e430707ee7fe81dbd7ebffe31f47686df00dfdf1e39df8dbfc5e6cf38d985e426f6ef897e8cdd417ec611511136ea3c5a
  • Further processing:
docker images | col 3 | xargsIMAGE 65a9e3ef7171 7c01ca6c30f2 9518620e6a0e 430707ee7fe8 1dbd7ebffe31 f47686df00df df1e39df8dbf c5e6cf38d985 e426f6ef897e 8cdd417ec611 511136ea3c5a
  • However, I also want to remove the preceding "IMAGE" character:
docker images | col 3 | xargs | skip 165a9e3ef7171 7c01ca6c30f2 9518620e6a0e 430707ee7fe8 1dbd7ebffe31 f47686df00df df1e39df8dbf c5e6cf38d985 e426f6ef897e 8cdd417ec611 511136ea3c5a
  • The complete writing is as follows:
docker rmi $(docker images | col 3 | xargs | skip 1)
Tip 9: Create your own command package

In bash, you can easily create your own command components. You can see what I wrote in bash:

function dur {  case $1 in  clone|cl)    git clone$2.git    ;;  move|mv)    git remote add bitbucket$(basename $(pwd)).git    git push --all bitbucket    ;;  trackall|tr)    #track all remote branches of a project    for remote in $(git branch -r | grep -v master ); do git checkout --track $remote ; done    ;;  key|k)    #track all remote branches of a project    ssh $2 'mkdir -p .ssh && cat >> .ssh/authorized_keys' < ~/.ssh/    ;;  fun|f)    #list all custom bash functions defined    typeset -F | col 3 | grep -v _ | xargs | fold -sw 60    ;;  def|d)    #show definition of function $1    typeset -f $2    ;;  help|h|*)    echo "[dur]dn shell automation tools"    echo "commands available:"    echo " [cl]one, [mv|move]"    echo " [f]fun lists all bash functions defined in .bashrc"    echo " [def] <fun> lists definition of function defined in .bashrc"    echo " [k]ey 

Through the above script, I can copy the ssh key to any website server-just type the dur key
User @ somehost.


You can try my. bashrc file, or you can write one by yourself. Do you have more skills? Please write in the following comments or send a private message to @ programmer's field of view. We look forward to hearing from you.

Bash logon and welcome information:/etc/issue,/etc/motd

Several common configuration files in Bash

Bash script 15-minute advanced tutorial

Job control instances of Bash and KSH shell in 10 Linux/Unix

Abnormal shell script running in Ubuntu: difference between Bash and dash

Bash script for statement if statement and various test statements

What is the Bash Shell build in command?

Share useful bash aliases and functions

This article permanently updates the link address:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.