Useful Tricks in the Linux Shell

(Click the public account above to quickly follow)

English: Techbar, Translation: Linux China/geekpi

linux.cn/article-2389-1.html

If you have good articles to submit, please click → here for details

I regularly use the Linux shell (Bash), but I often forget some useful commands or shell tricks. Yes, I can remember some commands, but they definitely won’t be used only once for specific tasks, so I started writing down these little tricks for the Linux shell in a text file on my Dropbox account, and now I’ve decided to share them with you. I will update this list in the future. Remember, some of these tips require additional software to be installed on your Linux distribution.

Useful Tricks in the Linux Shell

Check if a remote port is open in bash:

echo >/dev/tcp/8.8.8.8/53 && echo “open”

Pause a process:

Ctrl + z

Bring a process to the foreground:

fg

(Note: A suspended process does not execute. If you want it to run in the background, you can use the bg command and specify the job number obtained from the jobs command.)

Generate a random hexadecimal number, n is the number of characters:

openssl rand -hex n

Execute commands from a file in the current shell (Note: this file is not a bash script, such as .bashrc, bash_profile, etc.):

source /home/user/file.name

Extract the first 5 characters of a string:

${variable:0:5}

Open SSH debug mode (Note: very useful when you encounter SSH connection issues):

ssh -vvv user@ip_address

SSH connection using a pem key:

ssh user@ip_address -i key.pem

Use wget to get a complete directory listing to a local directory:

wget -r –no-parent –reject “index.html*” http://hostname/ -P /home/user/dirs

Create multiple directories at once:

mkdir -p /home/user/{test,test1,test2}

List processes and subprocesses in a tree format:

ps axwef

Create a war file:

jar -cvf name.war file

Test disk write speed:

dd if=/dev/zero of=/tmp/output.img bs=8k count=256k conv=fdatasync; rm -rf /tmp/output.img

Test disk read speed:

hdparm -Tt /dev/sda

Get the md5 value of text:

echo -n “text” | md5sum

Check XML syntax:

xmllint –noout file.xml

Extract a tar.gz file to a specified directory:

tar zxvf package.tar.gz -C new_dir

Get HTTP headers using curl:

curl -I http://www.example.com

Modify the timestamp of some files or directories (format: YYMMDDhhmm):

touch -t 0712250000 file

Download from ftp using wget:

wget -m ftp://username:password@hostname

Generate a random password (16 characters long in this example):

LANG=c < /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-16};echo;

Quickly create a backup of a file (extension is .bkp):

cp some_file_name{,.bkp}

Access Windows shares:

smbclient -U “DOMAINuser” //dc.domain.com/share/test/dir

Run a command from history (here it is the 100th command in history):

!100

Unzip to a directory:

unzip package_name.zip -d dir_name

Input multiple lines of text (press CTRL + d to exit):

cat > test.txt

Create an empty file or clear an existing file:

> test.txt

Update the date from the Ubuntu NTP server:

ntpdate ntp.ubuntu.com

netstat shows all listening TCP ports for IPv4:

netstat -lnt4 | awk ‘{print $4}’ | cut -f2 -d: | grep -o ‘[0-9]*’

Convert qcow2 image to raw format:

qemuimg convertfqcow2Oraw preciseservercloudimgamd64disk1.img

preciseservercloudimgamd64disk1.raw

Repeat a command and display its output (default repeats every 2 seconds):

watch ps -ef

Display all users:

getent passwd

Remount the root filesystem in read-write mode:

mount -o remount,rw /

Mount a directory (suitable when symbolic links do not work):

mount –bind /source /destination

Send DNS dynamic updates to DNS:

nsupdate <

Recursive grep all directories:

grep -r “some_text” /path/to/dir

List the 10 largest open files in the system:

lsof / | awk ‘{ if($7 > 1048576) print $7/1048576 “MB “$9 }’ | sort -n -u | tail

Display free memory in MB:

free -m | grep cache | awk ‘/[0-9]/{ print $4″ MB” }’

Open vim and jump to the end of the file:

vim + some_file_name

Clone a specific branch in git (in this example, the master branch):

git clone [email protected]:name/app.git -b master

Switch to another branch in git (in this example, the develop branch):

git checkout develop

Delete a branch in git (in this example, myfeature):

git branch -d myfeature

Delete a remote branch in git:

git push origin :branchName

Push a new branch to remote in git:

git push -u origin mynewfeature

Print the last cat command in history:

!cat:p

Run the last cat command in history:

!cat

Find all empty subdirectories in /home/user:

find /home/user -maxdepth 1 -type d -empty

Get lines 50 to 60 of text from test.txt:

< test.txt sed -n ‘50,60p’

Re-run the last executed command with sudo privileges (if it was: mkdir /root/test, the next will run: sudo mkdir /root/test) (Note: When you forget to use sudo for a command, you can re-execute it this way without typing the full command again):

sudo !!

Create a temporary RAM filesystem – ramdisk (please create the /tmpram directory first):

mount -t tmpfs tmpfs /tmpram -o size=512m

Grep for complete words (Note: not parts of other words):

grep -w “name” test.txt

Append text to a file with elevated permissions:

echo “some text” | sudo tee -a /path/file

List all supported kill signals:

kill -l

Generate a random password (16 characters long in this example):

openssl rand -base64 16

Do not record the last session in bash history:

kill -9 $$

Scan the network to find open ports:

nmap -p 8081 172.20.0.0/16

Set git email:

git config –global user.email “[email protected]

If you have uncommitted commits, sync with master:

git pull –rebase origin master

Move all files containing ‘txt’ in their names to /home/user:

find -iname “*txt*” -exec mv -v {} /home/user \;

Merge and display corresponding lines from two files line by line:

paste test.txt test1.txt

Progress bar in shell:

pv data.log

Send data to a server using netcat:

echo “hosts.sampleHost 10 `date +%s`” | nc 192.168.200.2 3000

Convert tabs to spaces:

expand test.txt > test1.txt

Skip bash history:

<<space>>cmd

Return to the previous working directory:

cd –

Split a large tar.gz file into several files (each 100MB), and restore:

splitb100m /path/to/large/archive /path/to/output/files

cat files* > archive

Get HTTP status value using curl:

curl -sL -w “%{http_code}\n” www.example.com -o /dev/null

When Ctrl + c does not work:

Ctrl + \

Get file owner:

stat -c %U file.txt

List block devices:

lsblk -f

Find files with trailing spaces:

find . -type f -exec egrep -l ” +$” “{}” \;

Find files indented with tabs:

find . -type f -exec egrep -l $’t’ “{}” \;

Print horizontal lines with “=”

printf ‘%100sn’ | tr ‘ ‘ =

If you found this article helpful, please share it with more people.

Follow ‘Linux Enthusiasts’ to improve your Linux skillsUseful Tricks in the Linux Shell

Useful Tricks in the Linux Shell

Taobao Code: Copy the following red content, then open Taobao to purchase

Fanpin Club, use ¥Geek T-shirt¥ for a sneak preview (long press to copy the entire text, open the mobile Taobao to enter the event content)

Leave a Comment