脚本问题

脚本问题

如何创建一个脚本,要求用户输入文件名然后创建该文件?

我已经尝试过这个:

#!/bin/bash
#Get Script name of this file and create it
#Get Author's name of this file
#Add the date this file is ran
#Add a "Hello"

echo -n "Please type Script destination file name: "
read 0

echo -n "Please type your name: "
read name

if [ -z "$0" ]
then
    echo "No Script name given."
else
    echo "#Script: $0" > $0
fi

if [ -z "$name" ]
then
    echo "No name given."
else
    echo "#Author: $name" >> $0
    echo "#Date: `date`"  >> $0
fi

答案1

您的问题是使用 $0 作为变量名。这是为被调用的脚本的名称保留的;尝试创建一个仅包含 的脚本echo $0;。此外,超出此范围的每个整数变量都为传递给脚本的参数保留。

以下是您脚本的更新版本,它按预期运行。我已将 $0 更改为 $filename,将 $name 更改为 $username。

#!/bin/bash
#Get Script name of this file and create it
#Get Author's name of this file
#Add the date this file is ran
#Add a "Hello"

echo -n "Please type Script destination file name: "
read filename

echo -n "Please type your name: "
read username

if [ -z "$filename" ]
then
    echo "No Script name given."
else
    echo "#Script: $filename" > $filename
fi

if [ -z "$username" ]
then
    echo "No name given."
else
    echo "#Author: $username" >> $filename
    echo "#Date: `date`"  >> $filename
fi

相关内容