快速查找 Linux shell 常用程序

批量修改文件名称

for file in ./*
do 
    echo mv -vf $file $begin_{file}_end
done

先查看上面命令的合理性,再重定向 | bash 执行

检查参数

if [ $# -ne 1 ]; then
    echo "$0 GPIO"
    exit 1
fi

仅限 root 用户

if [ "root" != "$(whoami)" ]; then
    echo "ONLY the root can do it!"
    exit 1
fi

重定向调试与日志

DBG()
{
    #echo $*             # enable  debug
    echo $* > /dev/null # disable debug
}

LOG_FILE=/tmp/$(basename $0).log
LOG()
{
    DBG  $*
    echo "$(date +%Y/%m/%d-%H:%M:%S) $*" >> $LOG_FILE
}

自动应答 expect 实现 scp 远程复制

PASSWD=your_passwd
REMOTE_USER=root
REMOTE_IP=192.168.1.102
REMOTE_DIR=/opt/log

expect << EOF
set timeout 10
spawn scp -r ${REMOTE_USER}@${REMOTE_IP}:${REMOTE_DIR} ./
expect {
    "password" {send "${PASSWD}\r";}
    "yes/no" {send "yes\r"; exp_continue;}
}
expect eof
EOF

输出批量数据到指定文件

DNS1=114.114.114.114
cat > ./ip.conf << EOF
{
    "eth0_conf": {
        "ipaddr": "192.168.1.99",
        "gateway": "192.168.1.1",
        "netmask": "255.255.255.0",
        "dns1": "$DNS1"
    }
}
EOF

判断语句

if grep -q root /etc/passwd ; then 
    echo "find root"
elif ! grep -q daemon /etc/passwd ; then
    echo "no daemon" 
fi

多个条件 AND 判断

if [ "$USER" = "root" ] && [ "$LOGNAME" = "root" ]; then
    echo "logname same as user are root"
else
    echo "logname is NOT user"
fi

多个条件 OR 判断

if [ "$USER" = "root" ] || [ "$LOGNAME" = "root" ]; then
    echo "is root"
else
    echo "is NOT root"
fi

for 循环

for entry in $(cat /etc/passwd)
do 
    echo $entry | cut -f1 -d:
done

while 循环

count=0
while [ $count -lt 10 ]
do
    echo $count
    count=$(expr $count + 1)
done

test 测试命令

数值比较

功能 命令 意义 助记词
相等 if [ $n1 -eq $n2 ] 检查 n1 是否与 n2 相等 equal
大于等于 if [ $n1 -ge $n2 ] 检查 n1 是否大于等于 n2 great equal
大于 if [ $n1 -gt $n2 ] 检查 n1 大于 n2 great than
小于等于 if [ $n1 -le $n2 ] 检查 n1 是否小于等于 n2 less equal
小于 if [ $n1 -lt $n2 ] 检查 n1 是否小于 n2 less than
不等于 if [ $n1 -ne $n2 ] 检查 n1 是否不等于 n2 not equal

字符串比较

功能 命令 意义
相同 if [ "$str1" = "$str2" ] 检查 str1 是否与 str2 相同
不同 if [ "$str1" != "$str2" ] 检查 str1 是否与 str2 不同
if [ "$str1" < "$str2" ] 检查 str1 是否比 str2 小
if [ "$str1" > "$str2" ] 检查 str1 是否比 str2 大
非 0 if [ -n "$str1" ] 检查 str1 的长度是否非 0
为 0 if [ -z "$str1" ] 检查 str1 的长度是否为 0

文件比较

功能 命令 意义 助记词
目录 if [ -d file ] 检查 file 是否存在并是一个目录 directory
存在 if [ -e file ] 检查 file 是否存在 exist
文件 if [ -f file ] 检查 file 是否存在并是一个文件 file
可读 if [ -r file ] 检查 file 是否存在并可读 read
非空 if [ -s file ] 检查 file 是否存在并非空 size
可写 if [ -w file ] 检查 file 是否存在并可写 write
可执行 if [ -x file ] 检查 file 是否存在并可执行 excute
属当前用户 if [ -O file ] 检查 file 是否存在并属当前用户所有 Owner
属当前组 if [ -G file ] 检查 file 是否存在并且默认组与当前用户相同 Group
if [ file1 -nt file2 ] 检查 file1 是否比 file2 新 new than
if [ file1 -ot file2 ] 检查 file1 是否比 file2 旧 old than
posted @ 2022-08-04 15:59  KevinAshton  阅读(55)  评论(0编辑  收藏  举报