shell 如何在执行过程中不运行文件的情况下将别名写入文件?

2wnc66cl  于 2023-05-01  发布在  Shell
关注(0)|答案(2)|浏览(80)

我正在尝试写一个函数,创建一个别名并将其写入文件。我这样编写它,以便用户输入别名的名称为$1,使用别名的路径为$2。我有两个变量$alias_name$path_to_add,分别存储$1 $2。然后我有第三个变量$jp_string,看起来像这样:
`jp_string=“alias $alias_name='cd $path_to_add'"
该函数检查两个参数是否都存在,如果存在,则使用它们填充$jp_string的空格,然后将$jp_string写入文件。除了当我运行脚本时,字符串中的“alias”一词会作为命令运行,而不是仅仅作为字符串来处理之外,一切都很正常。如何编写$jp_string变量,使其仅被解析为双引号中的字符串而不是命令?任何帮助都很感激,我在其他地方寻找答案,并不断接近,但不完全。我了解到,你需要将特殊的符号,如'$'转义为$,以便在字符串中使用它,但你如何“转义”命令,如'alias'或'cd'在字符串中?
所以在这个函数中,如果我传入例如“myalias”和“my/new/path”作为args $1和$2。这是我得到的输出错误:
addPathToJumpPoints:11:未找到alias myalias ='cd'

function addPathToJumpPoints() {
    
    alias_name=$1
    path_to_add=$2
    xjp_file=$XFILES/.xtest
    jp_string=""

    if [[ ! -z $alias_name ]]; then
    
        if [[ ! -z $path_to_add ]]; then
            $jp_string="alias $alias_name='cd $jp_path'"
            
            if [[ -d $path_to_add ]]; then                      
                echo $jp_string >> $xjp_file
        echo "Jump point to: [$path_to_add] was created!"
            else
        echo "[$path_to_add] does not exist, would you like to create it? (y/n)"
            read make_path
                
                if [[ $make_path == "y" ]]; then
            mkdir $path_to_add
                    echo $jp_string >> $xjp_file
                    echo "$path_to_add and a jump point to it were created!"
                elif [[ $make_path == "n" ]]; then
                    echo "Should a jump point be made regardless? (y/n)"
                    read make_jp
            
                    if [[ $make_jp == "y" ]]; then
                        echo $jp_string >> $xjp_file
                        echo "Jump point to [$path_to_add] was created!"
                    elif [[ $make_jp == "n" ]]; then
                        echo "No jump point was created."
                    else
                    echo "Invalid answer!. Enter only 'y' for yes and 'n' for no."
                    fi
                
                else
                echo "Invalid answer. Enter only 'y' for yes and 'n' for no."
        fi
            fi
        else
            echo "Please provide a path to create a jump point"
        fi
    else
        echo "Please provide an alias and a path to create a jump point!"
    fi
}
fkvaft9z

fkvaft9z1#

这条线

$jp_string="alias $alias_name='cd $jp_path'"

1.要声明一个字符串,可以像STRING_NAME=“some string”这样
1.我没有看到任何地方定义了jp_path。它不应该是输入$2,i吗?例如,path_to_add?
尝试将该行更新为以下内容:

jp_string="alias $alias_name='cd $path_to_add'"
cigdeys3

cigdeys32#

好吧,我知道问题所在了。我真的很感谢大家的帮助。我在作业中使用了'$'
$jp_string=“alias $alias_name='cd $path_to_add '”
我应该这么做的:
jp_string=“alias $alias_name='cd $path_to_add'"

相关问题