Linux Shell 日常编程实用句式速查,注意以下例子如无特殊说明都是 bash 语法。
#!/usr/bin/env bash #!/usr/bin/bash
rep=${ENV_YOUR_KEY:-"my-default-value"}
current_dir=$(cd `dirname $0`;pwd)
chmod +x `find . -name '*.sh'`
log_file=/var/log/test.log echo "This line will echo to console and also write to log file." | tee -a ${log_file}
username_line="username=test" #key is username key=${username_line%=*} #val is test val=${username_line#*=}
#trim string by echo val_trim=$(echo -n ${val})
apps=(foo bar) for app in ${apps[@]} do echo "$app" done
# ls 转数组,根据需要 grep arrs=($(ls helmfiles/apps | grep -v .yaml))
# 获取当前 helm list 命令输出结果,通过换行分割成数组 IFS=$'\n' helm_list=($(helm list --no-headers)) for hm in ${helm_list[@]} do # 对每一行进行解析按 Tab 再分割成数组 IFS=$'\t' hma=($hm) echo "helm upgrade --install ${hma[0]} ${hma[0]} --version ${hma[6]} --reset-values 2>&1" done
log=my-log-file # 原地排序覆盖原文件 sort -o ${log} ${log}
img=docker.io/nginx:1.20 repo=docker.io # if 判断字符串是否以 repo 开头 if [[ $img == $repo* ]]; then # 注意这里 +2 suffix=$(echo $img | cut -c$((${#repo}+2))-) # 输出 nginx:1.20 echo "$suffix" fi
或
echo "nginx" | grep -E "nginx|tomcat" echo "tomcat" | grep -E "nginx|tomcat" echo "envoy" | grep -E "nginx|tomcat"
ct=$(TZ=UTC+8 date "+%Y%m%d%H%M")
# check if run as root user if [[ `id -u` -ne 0 ]]; then echo "You need root privileges to run this script." fi