适用于Bash编程初学者小例子–第三篇

替换掉字符串里的前倾斜杠符号,换成下划线,然后存储到一个变量里。

#!/bin/bash

str1="Seismic_Dataset/Others/Image_repository"

dataset_name="$(tr "//" "_" <<< $str1)"
echo "$dataset_name"

*注意,这里展示了一个把某一个命令的结果以字符串的形式,保存到一个变量中的方法。


拼接一个由几个字符串变量组成的字符串。

#!/bin/bash

str1="Seismic_Dataset_Others_Image_repository"

n=3

dataset_name="${n}"".""${dataset_name}"

echo $dataset_name


等待用户输入一个Enter,然后继续执行。

#!/bin/bash
echo "Please make sure the following:"
echo "1. Cluster is empty."
echo "2. Quota is enabled."

read -r -s -p $'Press enter to continue...    \n'

echo "I see you are ready."


从完整路径里得到最末端的文件名,或目录名。

#!/bin/bash

line1="/tmp/Seismic_Dataset/Others/Image_repository"
dirname2="$(basename $line1)"
echo $dirname2


从一个字符串中提取一个数字。

#!/bin/bash
output="Started job [14]"
jobid=$(echo $output | tr -dc '0-9')
echo $jobid


调用函数,并传参数,调用之后用返回值。

#!/bin/bash

function afun () {
     local jobid=$1
     local jobname=$2
    
     printf "Job id is %s, job name is %s. \n" $jobid $jobname
    
     return 34
}

afun 12 "QuotaScan"
echo $?


判断文件夹是否存在,如果没有则创建一个。

#!/bin/bash
DIR_OF_RESULTS2="/home/yunlong/DRR_RESULTS2"
mkdir -p "$DIR_OF_RESULTS2"
mkdir -p "$DIR_OF_RESULTS2"


检查一个mount是否存在。

#!/bin/bash
if mount | grep /mnt/tmesandbox81 > /dev/null; then
     echo "yay"
else
     echo "nay"
fi


逐行读取一个文件,把内容存入数组中。

#!/bin/bash

IFS=$'\n' read -d '' -r -a lines < /home/yunlong/source_datasets.txt

printf "line 1: %s\n" "${lines[0]}"
printf "line 2: %s\n" "${lines[1]}"

# all lines
echo "${lines[@]}"


参考资料

=============

https://unix.stackexchange.com/questions/162221/shortest-way-to-replace-characters-in-a-variable

https://stackoverflow.com/questions/2871181/replacing-some-characters-in-a-string-with-another-character

https://www.tweaking4all.com/software/linux-software/bash-press-any-key/

https://linuxconfig.org/how-to-extract-a-number-from-a-string-using-bash-example

https://stackoverflow.com/questions/9422461/check-if-directory-mounted-with-bash

posted on 2020-07-09 17:54  中道学友  阅读(118)  评论(0编辑  收藏  举报

导航

技术追求准确,态度积极向上