有条件地在变量前加上斜杠

卡格曼德·安徒生

我以为我可以解决这个问题。我以前写过更复杂的Shell脚本,所以我认为这样做很容易。我现在已经浪费了一个小时,并且把头发扯掉了,因为我什么都没做,而且我无法在网上找到任何可用的帮助。

我要做的就是等效于以下简单的C#代码片段:

var splat = "some/path";
if (!splat.StartsWith("/"))
{
    splat = $"/{splat}";
}

接受一个字符串参数。如果以斜杠开头,则什么也不做。如果不是以斜杠开头,则将其添加到字符串变量的前面。

我如何在bash脚本中完成这项显而易见的艰巨任务?

我的尝试:

#!/bin/bash

dir="/root/home"
sub_dir=$1

echo "argument given: '"$sub_dir"'"

if [ ! -z $sub_dir ]
then
        echo "before: "$dir$1
        if [[ "${sub_dir}" != *'/' ]]; then
                echo "starts with slash!"
        else
                echo "doesn't start with slash!"
                $sub_dir="\/"${sub_dir}
                echo "slash added: "$sub_dir
        fi
else
        echo "argument not given"
        echo $dir
fi

echo "$dir$sub_dir"

我也尝试过使用regex作为条件,但没有成功:

if [[ "$HOST" =~ ^user.* ]]; then

我也没有找到一种方法来传递以斜杠开头的参数或创建以斜杠开头的字符串,但由于某种原因而不将其视为文件路径而不是字符串(随后导致错误),因此不存在这种方法。

编辑:bash --version如果有什么区别,那就说它是GNU bash版本5.0.17。

Ajinzrathod
#!/bin/bash

dir="/root/home"
sub_dir=$1

echo "argument given: '"$sub_dir"'"

if [ ! -z $sub_dir ]
then
    echo "before: "$dir$1
    if [[ $sub_dir = '/'* ]]; then
        echo "Start with slash"
    else
        echo "doesn't start with slash!"
        slash="/"
        sub_dir="${slash}${sub_dir}"
        echo "slash added: "$sub_dir
    fi
else
    echo "argument not given"
    # echo $dir
fi

echo "$dir$sub_dir"

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章