Table of content back
- Bash/Shell handy snippet
- Run next command if the previous one is failed
- Read a file line by line assigning the value to a variable
- Simple multiple files/folders maker
- Loop in a string array
- Run multiple replicated command with multiple files
- Do multiple silent task
- Backgroud process to file (stdout + stderr)
- Update multiple files' name in 1 command
- Manage IP tables
telnet
sed
common use cases- Concatenate file common use cases
- Append content to file with sudo privileges
- Create json file with variable in bash
cmd1 && echo "Success" || echo "Failed"
while read -r line; do
echo "Text read from file: $line"
done < my_filename.txt
mkdir -p project/{app,frontend,backend}
touch {main,variables,provider}.tf
b=("aa" "ab"); for t in ${b[@]} ; do echo $t ; done
echo ${#b[@]} # get array length
for a in *.yml; ansible-playbook "$a" --syntax-check ; done
for file in $(find /home/ec2-user/ -type f); do cmd1 $file | cmd2 &disown ; done
command > file.log 2>&1 &
Explanation:
>
stdout to file2>&1
: redirect stderr to stdout&
: run process in backgroud
find . -name "*_f"| sed "s/.\///g" | while read f ; do mv "$f" "${f%?????}_f"; done
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
- Without interaction
echo -e '\x1dclose\x0d' | telnet {$IP_ADDRESS} {$PORT}
- Multiple IPs with SSH port
PORT=22 list=("172.29.211.1" "172.29.211.2") ; for ip in "${list[@]}" ; do echo -e '\x1dclose\x0d' | timeout 2 telnet $ip {$PORT} && echo "connect $ip success" || echo "connect $ip failed" ; done
- Replace string directly on file
sed -i 's/pattern1/pattern2/g' filename
- 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 "\nnfs-uuid:/ /mnt/efs nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0" | sudo tee -a /etc/fstab
- Create multiple-lines text file as sudoer
sudo tee /etc/systemd/system/custom-service.service > /dev/null <<-EOF
# *****************************************************************
# *********************** Custom Service **************************
# *****************************************************************
[Unit]
Description=Custom Service
After=network.target
[Service]
ExecStart=/start/script/for/custom-service
ExecStop=/stop/script/for/custom-service
User=root
[Install]
WantedBy=multi-user.target
EOF
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