Initializing a variable with echo

10,588

Solution 1

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

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

Solution 2

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)
Share:
10,588

Related videos on Youtube

Gui Montag
Author by

Gui Montag

Updated on September 18, 2022

Comments

  • Gui Montag
    Gui Montag over 1 year

    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?

  • Gui Montag
    Gui Montag over 8 years
    That gives me the error -bash: 123: command not found
  • YoMismo
    YoMismo over 8 years
    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
  • Gui Montag
    Gui Montag over 8 years
    Oh, nvm I was just doing some wrong syntax it seems to work fine. Thanks.