{if[["$1"=~"$2"]];thenecho\"$1\" contains \"$2\"elseecho\"$1\" does not contain \"$2\"fi} check_substr"$1""$2" 这个脚本判断传入的第二个参数是否为第一个参数的子字符串。 具体执行结果如下: $./check_substr.sh"This is a test string""test string""This is a test string"...
$ ./check_substr.sh 'This is a test string' 'test string' 'This is a test string' contains 'test string' $ ./check_substr.sh 'This is a test string' 'is a test' 'This is a test string' contains 'is a test' $ ./check_substr.sh 'This is a test string' 'isa test' 'This...
ifgrep-q root $1 # 参数提供的文件中,如果含有root字符串,则返回File contains at last on occurence of root # 其中-q用来阻止echo的输出grep获得的内容 then echo"$1 contains at last on occurence of root" else echo"$1 does not contain" fi exit0 并chmod777test.sh, 执行: ./test.h/etc/pas...
Checking if a string contains a substring is one of the most basic and frequently used operations in Bash scripting. After reading this tutorial, you should have a good understanding of how to test whether a string includes another string. You can also use other commands like awk or sed for...
Using the “If -Z” Statement Sometimes, it is required to check if a string variable is empty or if it contains a string of zero length. There are many options in Bash to do this task. Using the “-z” option with the “if” statement is one of the ways to check whether a vari...
echo"$1 contains at last on occurence of root"elseecho"$1 does not contain"fi exit0并chmod777test.sh, 执行: ./test.h /etc/passwd 之后,返回 File contains at last on occurence of root4.一个if/then结构可以包含多级比较和tests(嵌套)if[ condition -true] ...
TestFile1 does not exist or is empty. 现在创建一个空文件用来测试: [student@studentvm1 testdir]$ File="TestFile1" ; touch $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; else echo "$File does not exist or is empty." ; fi ...
TestFile1 does not exist or is empty. 向文件添加一些内容,然后再测试一次: [student@studentvm1 testdir]$ File="TestFile1" ; echo "This is file $File" > $File ; if [ -s $File ] ; then echo "$File exists and contains data." ; else echo "$File does not exist or is empty." ...
How totest whether a string$strcontains another string$needleinBash? You can use this piece ofBashscript: [["$str"== *"$needle"* ]] A usage example: $ str="abcde hello"$ needle1="deh"$ needle2="de hello"$ [["$str"== *"$needle1"* ]] &&echo"matched"$ [["$str"== *"$...
Exercise 4: Write a script that accepts two string arguments. The script should check if the first string contains the second argument as a substring. Hint: Refer to the previous chapter onbash strings You may discuss your solution in the Community: ...