简体   繁体   English

bash实现目录中的变量

[英]bash implement variable in a directory

I have a serial number: SX410-251509-0171 我有序列号:SX410-251509-0171

In my code I extract the 2 digit year (15 in example above) and the 2 digit week (09 in the example above) and want to use these in a file directory. 在我的代码中,我提取了两位数的年份(在上面的示例中为15)和两位数的星期(在上面的示例中为09),并希望在文件目录中使用它们。

#! /bin/bash           

year=${serial:8:2}
week=${serial:10:2}
dir="/home/jbon/20$year/$week/$serial/run0/output_log"
echo $dir    

When I run this code I'm getting the following output: 运行此代码时,我得到以下输出:

/run0/output_log015/09/SX410-251509-0171 / run0 / output_log015 / 09 / SX410-251509-0171

I'm guessing the issue is around how I am using the variables in the string. 我猜问题出在我如何使用字符串中的变量。

It sounds like you are running the script with sh , not bash , and your sh links to a shell other than bash that doesn't recognize the substring expansion operator. 听起来您是使用sh而不是bash运行脚本,并且您的sh链接到bash以外的无法识别子字符串扩展运算符的外壳程序。 However, you can rewrite it in a POSIX-compliant fashion: 但是,您可以按照POSIX兼容的方式重写它:

yearweek=${serial##*AB}   # Drop everything up to and including AB
yearweek=${yearweek%%-*}  # Drop everything from - onward
year=${yearweek%??}       # Drop the two-digit week
week=${yearweek#??}       # Drop the two-digit year

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM