永发信息网

关于一个shell script 脚本的问题

答案:1  悬赏:20  手机版
解决时间 2021-12-26 02:47
  • 提问者网友:自食苦果
  • 2021-12-25 18:50
今天第一次写这个东西,对于他基本是完全不晓得,我应该完全按照书上的敲的,但运行的时候却出错了 ,希望能得到大家的指导,帮忙看下是哪儿的问题

1 #!/bin/bash
2 #Program:
3 # Program creates three files,which named by user's input
4 # and date command.
5 #History:
6 #$date
7
8 #1.input user name
9 echo -e "I will use 'touch' command to create 3 file."
10 read -p "Please input your filename:" fileuser
11
12 #2.****
13 filename=${fileuser:-"filename"}
14 date1=${date --date='1 days ago' +%Y%m%d}
15 date2=${date --date='2 days ago' +%Y%m%d}
16 date3=${date +%Y%m%d}
17 file1=${filename}${date1}
18 file2=${filename}${date2}
19 file3=${filename}${date3}
20
21 touch "${file1}"
22 touch "${file2}"
23 touch "${file3}"

上面的是代码,一下是错误信息
cxd@cxd115:/var/tmp/scripts$ sh sh03.sh
-e I will use 'touch' command to create 3 file.
Please input your filename:yes
sh03.sh: 14: sh03.sh: Bad substitution
最佳答案
  • 五星知识达人网友:人间朝暮
  • 2021-12-25 19:55
sh 加上-x 可以看到执行过程,发现有报错,是${}引起的,换成``就可以了
# sh -x ddd
+ echo -e 'I will use '\''touch'\'' command to create 3 file.'
I will use 'touch' command to create 3 file.
+ read -p 'Please input your filename:' fileuser
Please input your filename:a
+ filename=a
ddd: line 14: ${date --date='1 days ago' +%Y%m%d}: bad substitution
ddd: line 15: ${date --date='2 days ago' +%Y%m%d}: bad substitution
ddd: line 16: ${date +%Y%m%d}: bad substitution
+ file1=a
+ file2=a
+ file3=a
+ touch a
+ touch a
+ touch a

改成以下就可以了:
#!/bin/bash
#Program:
# Program creates three files,which named by user's input
# and date command.
#History:
#$date

#1.input user name
echo -e "I will use 'touch' command to create 3 file."
read -p "Please input your filename:" fileuser

#2.****
filename=${fileuser:-"filename"}
date1=`date --date='1 days ago' +%Y%m%d`
date2=`date --date='2 days ago' +%Y%m%d`
date3=`date +%Y%m%d`
file1=${filename}${date1}
file2=${filename}${date2}
file3=${filename}${date3}

touch "${file1}"
touch "${file2}"
touch "${file3}"
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯