Skip to content

Instantly share code, notes, and snippets.

@vanvuvuong
Last active April 1, 2024 08:01
Show Gist options
  • Save vanvuvuong/a196b5ccc2fdb668e17b4355385e2204 to your computer and use it in GitHub Desktop.
Save vanvuvuong/a196b5ccc2fdb668e17b4355385e2204 to your computer and use it in GitHub Desktop.
Linux Advanced Commands Notes

Run next command if the previous one is failed

cmd1 && echo "Success" || echo "Failed"

Read a file line by line assigning the value to a variable

while read -r line; do
    echo "Text read from file: $line"
done < my_filename.txt

Simple multiple files/folders maker

mkdir -p project/{app,frontend,backend}
touch {main,variables,provider}.tf

Loop in a string array

b=("aa" "ab"); for t in ${b[@]} ; do echo $t ; done

Run multiple replicated command with multiple files

for a in *.yml; ansible-playbook "$a" --syntax-check ; done

Do multiple silent task

for file in $(find /home/ec2-user/ -type f); do cmd1 $file | cmd2 &disown ; done

Update multiple files' name in 1 command

find . -name "*_f"| sed "s/.\///g" | while read f ; do mv "$f" "${f%?????}_f"; done

IP tables

iptables -P INPUT ACCEPT
iptables -I INPUT 1 -p tcp -s 159.89.202.45 -j ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P INPUT DROP

Telnet without interaction

echo -e '\x1dclose\x0d' | telnet IP_ADDRESS PORT

Telnet multiple IPs with same port

list=("172.29.211.1" "172.29.211.2") ; for ip in "${list[@]}" ; do echo -e '\x1dclose\x0d' | timeout 2 telnet $ip 22 && echo
"connect $ip success" || echo "connect $ip failed" ; done

Checking MySQL server info

mysql> STATUS;
mysql> SELECT VERSION();
mysql> SHOW VARIABLES LIKE 'version%';

FIND common use cases:

Find files & folder that changing less than 5 minutes except ones in /proc, /sys, /var, /run & /mnt (-prunt option will ignore the whole tree directory)

find / -cmin -5 ! -path '/proc/*' -prune ! -path '/sys/*' -prune ! -path '/var/*' -prune ! -path '/run/*' -prune ! -path '/mnt/*' -prune

Find files in current folder that have name pattern ~ sam* & replace content in those file from sample to sample2

find . -name "sam*" -type f -exec sed -i 's/sample/sample2/g' {} \;

Find anything that change more than 24 days and size more than 15Gb

find . -ctime +24 -size +15G

Showing empty files content in level 1 of the home directory

find ~ -maxdepth 1 -size 0c -exec ls -lht {} \;

Finding the line that contain text "CLS" in all the executable file in current folder

find . -type f -executable -exec grep "CLS" {} \;

Execute complicate cmd command with some pdf files

find . -name '*pdf' -exec bash -c 'cmd {}' \;

Find all folders in 1 parent folder and list them to a text file

find parent-folder -maxdepth 1 -mindepth 1 -type d -printf '%f\n' >children_foldername

SED common use cases:

Replace string directly on file

sed -i 's/pattern1/pattern2/g' filename

CAT common use cases:

Insert multiple-lines text in to new file

cat <<EOF > filename
Multiple
Lines
Text
Data
EOF

Appending multiple-lines text in to existed file

cat <<EOF >> filename
Multiple
Lines
Text
Data
EOF

Append text with sudoers (persistent mount point)

echo -e "\nfs-04a12fd8a21cfaddd.efs.ap-northeast-1.amazonaws.com:/  /mnt/efs nf
s4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0" | sudo tee -a /etc/fstab

TEE with sudo privileges

Create multiple-lines text file as sudoer

sudo tee /etc/systemd/system/DataSpiderServer.service > /dev/null <<-EOF
# *****************************************************************
# *********************** DataSpider Server ***********************
# *****************************************************************

[Unit]
Description=DataSpider Server
After=network.target mnt-efs.mount

[Service]
ExecStart=/mnt/efs/dataspider/server/bin/DataSpiderServer
ExecStop=/mnt/efs/dataspider/server/bin/Shutdown
User=root

[Install]
WantedBy=multi-user.target
EOF

Cat json file with variable in bash:

SAMPLE='
{
    "Comment": "Update DNSName.",
    "Changes": [
        {
            "Action": "UPSERT",
            "ResourceRecordSet": {
                "Name": "alex.",
                "Type": "A",
                "AliasTarget": {
                    "HostedZoneId": "######",
                    "DNSName": "$bar",
                    "EvaluateTargetHealth": false
                }
            }
        }
    ]
}
'
echo "${SAMPLE}" | tee output-file-path.json > /dev/null

Backgroud process to file (stdout + stderr)

command > file.log 2>&1 &

Explaination:

  • > stdout to file
  • 2>&1: redirect stderr to stdout
  • &: run process in backgroud
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment