So, I'm trying to store a part of the name of a file into a variable for other uses. So, if my file was named hello123.txt and I want to store the 123 part. So I try

num= echo $file |cut -c6-8

But all it does is echo the 123 and not store that value in the variable. How do I make it so that it just initializes the variable and not do anything else?


You could use echo, or just use shell parameter substitution:

$ file=123456789
$ num=$(echo "$file" | cut -c6-8); echo $num
$ num=${file:5:3}; echo $num     # substring of length 3 starting from 6th char

You need to enclose your command in $() or `` which will execute it and store in the variable the result value.

num=$(echo $file |cut -c6-8)
  • That gives me the error -bash: 123: command not found – Gui Montag Oct 1 '15 at 15:26
  • Does num=`echo $file |cut -c6-8` or num=$(echo $file |cut -c6-8) give you the error you mentioned???? cause it is working for me file="hola que tal";num=$(echo $file |cut -c6-8);echo $num returns que – YoMismo Oct 1 '15 at 15:36
  • Oh, nvm I was just doing some wrong syntax it seems to work fine. Thanks. – Gui Montag Oct 1 '15 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.