bash语法

if 判断语句

var=$1
if [ $var -eq 1 ]; then
    echo 'var is 1'
elif [ $var -eq 2 ]; then
    echo 'var is 2'
else
    echo 'var is not 1 and 2'
fi

# case 选择语句, 即我们一般语法中的switch
case $var in
    'value1')
        echo -e 'var is value1 for first place'
    ;;

    'value2')
        echo -e 'var is value2 for second place'
    ;;

    *)
        echo -e 'var is eq value1 or value2, so this is a default ouptput'
    ;;
esac

for 循环语句

  • case 1 输入数字
for i in 1 2 3 4 5 6
do 
    echo -e "current value is $i"
done
  • case 2 输出字符串
for i in 'this is a string , will be output one by one'
do 
    echo $i
done
  • case 3 输出文件夹
for file in $HOME/.*
do
    echo $file
done
  • case 4 输出数组
for ele in (1,2,3,4,hello)
do
    echo $ele
done
  • case 5 遍历文件夹
for file in <path>
do
    if test -f $file;then
       rm $file
    else
        echo "$file is a dir"
    fi
done




代码示例1(迁移文件夹):

#!/bin/bash

# 检查参数
if [ ! -n "${1}" ];then
    echo "请指定一个目录来进行迁移: ls ~/Library/Application\ Support/"
    exit -1
fi
Entity=$1
# 检查路径是否存在
SourceFolder="${HOME}/Library/Application Support/${Entity}"
if [ ! -d "${SourceFolder}" ];then
    echo "${SourceFolder}目录不存在!"
    exit -1
fi
echo "即将迁移:${SourceFolder}"

# 检查覆盖
if [ -L "${SourceFolder}" ];then
    echo "源路径已经是符号连接"
    ls -l "${SourceFolder}"
    exit -1
fi

# 确定目标设备
TargetDevice="/Volumes/External"
read -p "目标设备为(默认 ${TargetDevice}): " InputTargetDevice
if [[ -n $InputTargetDevice && "$TargetDevice" != "$InputTargetDevice" ]];then
    TargetDevice=$InputTargetDevice
fi
TargetFolder="${TargetDevice}/Library/Application Support/${Entity}"
if [ -d "${TargetFolder}" ];then
    echo 目标路径"${TargetFolder}已经存在,将进行覆盖才做"
fi

# 准备迁移
echo "正在准备迁移 ${SourceFolder} => ${TargetFolder}"
mkdir -p "${TargetDevice}/Library/Application Support" \
    && mv -vn "${SourceFolder}"/* "${TargetFolder}/" \
    && rmdir "${SourceFolder}" \
    && ln -s "${TargetFolder}" "${SourceFolder}" \
    && echo "迁移成功!" \
    && exit 0

echo "迁移失败!"

发表评论

电子邮件地址不会被公开。 必填项已用*标注