
如何建立一個腳本來詢問使用者檔案名稱然後建立該檔案?
我已經嘗試過這個:
#!/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