终端输出

终端输出

我想写一个regex,将shellscript用户输入路径与用户进行比较$HOME。然后,如果用户输入路径包含用户,它将引发错误$HOME。主文件夹通常以 开头,/ort/home/ort部分不是必须的。当我运行时,它总是给出一个,valid path尽管我显然输入了一个无效路径。我做错了什么?谢谢。如有必要,请参考以下链接[1] 以了解如何regexshellscript

我的尝试如下

#!/bin/bash

function user_input () {

        read -p "Type the path for project1:" user_path

        string1="${HOME}"
        echo "$string1"

        if [ "$user_path" = "$string1 | /ort/home/+.* |  .*+/home/+.*"  ]; then 
             echo "Not a valid path, contains $HOME directory"        
        else
             echo "valid path"
        fi
}

function main() {

user_input
}

main

终端输出

请注意,第一个条目是有效路径,其他两个是无效路径。

jenny@server32:~$ ./test.sh 
Type the path for project1:/scratch/random
/ort/home/j/jen
valid path

jenny@server32:~$ ./test.sh 
Type the path for project1:/ort/home/j/jen
/ort/home/j/jen
valid path

jenny@server32:~$ ./test.sh 
Type the path for project1:/ort/home
/ort/home/j/jen
valid path

[1]https://stackoverflow.com/questions/2237080/how-to-compare-strings-in-bash

答案1

case命令用途全局通配符它们非常容易使用:

case "$user_path" in
    "$HOME"*) echo "Error: path cannot be in your HOME" ;;
    */home/*) echo "Error: cannot have 'home' in the path" ;;
    *) echo "Thank you, valid path" ;;
esac

相关内容