mimicocotopus mimicocotopus - 1 year ago 45
Bash Question

How can remove the extension of a filename in a shell script?

What's wrong with the following code?

name='$filename | cut -f1 -d'.''

As is, I get the literal string '$filename | cut -f1 -d'.' but if I remove the quotes I don't get anything. Meanwhile typing

"test.exe" | cut -f1 -d'.'

in a shell gives me the output I want, "test". I already know $filename has been assigned the right value. What I want to do is assign to a variable the filename without the extension.

Answer Source

You should be using $(command) when you want to execute a command in script/command.

So your line would be

name=$(echo $filename | cut -f 1 -d '.')

Code explanation:

  1. echo get the value of the variable $filename and send it to standard output
  2. We then grab the output and pipe it to the cut command
  3. The cut will use the . as delimiter (also known as separator) for cutting the string into segments and by -f we select which segment we want to have in output
  4. Then the $() wrapper will get the output and return it's value
  5. The returned value will be assigned to the variable named name