Categories Linux

[Linux] Useful Commands in Shell [Vi]

Root user thường có #, normal user thường có $.

Thông tin của user ở /etc/passwd

Quit vim không lưu bằng :q!, lưu xong quit :wq

Để search file theo một từ khóa:

grep TU_KHOA FILE_NAME

Grep cũng search được directory recursively:

grep -r TU_KHOA DIR

Có thể dùng printf để in ra formatted text:

name="World"
printf "Hello, %s\n" "name"

Có thể dùng biến như sau. Tạo file với nội dung:

printf "Hello, %s\n" "$1"

Chạy file: ./FILENAME.sh world


Dùng read để đọc dòng lệnh đầu tiên từ stdin vào:

#!/bin/bash
echo "who are you?"
read name
echo "hello $name"

Dùng expr để tính toán. Lưu ý thêm biểu thức ở bên trong $(), term sau expr phải có cách, và kí tự đặc biệt như >, * phải có dấu thoát:

echo "$(expr 3 + 5)"
echo "$(expr 3 \> 5)" # print 1

Ví dụ để tạo bash script với argument (có kèm giải thích):

deploy=false
uglify=false
while (( $# > 1 )); do case $1 in # kiểm tra số biến đầu vào lớn hơn 1
 --deploy) deploy="$2";; # cú pháp của case: case <var> in <s>xuống dòng</s> --<giá trị>) <s>...code..</s> ;;)[1-inf] *) <s>break</s>; esac;
 --uglify) uglify="$2";;
 *) break;
esac;
shift 2 #dịch đọc biến đi 2 đơn vị
done
$deploy && echo "will deploy... deploy = $deploy" # chỉ true mới chạy
$uglify && echo "will uglify... uglify = $uglify

Lệnh đọc dung lượng files, directories và ổ nhớ:

df -hTs # để in các file system, -T để in type, -h human readable, -s summary
du -h # để in files và directory memory usage

Để đọc kết quả trả về command output:

while IFS=":" read -r user _
do
 # "$user" holds the username in /etc/passwd
 echo $user
done < <(grep "/bin/bash" /etc/passwd)

IFS là để specify seperator. Khi đọc từng dòng thì data đầu tiên đọc vào user


xargs để chạy command với input piped ở đằng trước. Ví dụ:

find . -name "*.txt" -print0 | xargs -0 rm

-print0 để cài input seperator bằng \0, và -0 để cài interpret seperator cũng bằng \0

More From Author

Leave a Reply

Your email address will not be published. Required fields are marked *