0

I have an input variable $1, and I only want the first four character of $1 and store it to a variable (i.e. rundate). I have the current code below:

rundate=$(echo $1 | cut -c1-4)
echo $rundate 

but when I run my script

test.sh 20161234

it returns an error message

syntax error: `rundate=$' unexpected

Could anyone help here? Thank you!

Edit1: if I just have the following:

echo $1 | cut -c1-4

I will be able to print it as 2016. However, I want to assign it to a local variable that I can use it later in the script.

Edit2: Not too sure whether it's old bash or new bash, but if I change the code to

rundate='echo $1 | cut -c1-4'
echo $rundate

I will get

echo $1 | cut -c1-4
Mahesh Khond
  • 1,297
  • 1
  • 14
  • 31
Kyle Gong
  • 27
  • 4
  • old bash? try `rundate=\`echo $1 | cut -c1-4\`` (backquotes) – Jean-François Fabre Nov 14 '16 at 20:06
  • @Jean-FrançoisFabre. Hi Jean, I just tried it, but it returns echo $1 | cut -c1-5 (a string I guess) instead of the correct answer – Kyle Gong Nov 14 '16 at 20:11
  • backticks, not single quotes. See the duplicate link anyway. – Jean-François Fabre Nov 14 '16 at 20:15
  • If the contents of `$1` is a date stamp in yyyy-mm-dd format then `${1%%-*}` gets you the year part without external processes. (Really old `sh` does not support the `%%` variant, though, and will require something a bit more complex. Try `${1%${1#????}}` perhaps then.) – tripleee Nov 15 '16 at 12:30

0 Answers0