cannot pass a echo output to a variable in bash

Hi,

I have a problem with passing a echo output into a variable in bash

file='1990.tar'
NAME='echo $file | cut -d '.' -f1';
echo $NAME

the result is

echo $file | cut -d . -f1

however with this one,

#!/bin/bash
file='1990.tar'
echo $file | cut -d '.' -f1

the result is what I need:

1990

How could I pass the right filename 1990 to the variable "NAME", thanks!

file='1990.tar'
NAME=$(echo "${file}" | cut -d '.' -f1)
echo "${NAME}"

The $( ) notation is preferred.

The problem in your original script was that you used single quotes not backticks to enclose the executable pipeline.

file='1990.tar'
NAME=`echo $file | cut -d '.' -f1`
echo $NAME
1 Like

It's your quoting. You probably intended to use back ticks, but this is better.

NAME=$( echo $file | cut -d '.' -f1 )

You could also do it without having to invoke another process (best):

NAME="${file%.*}"

The syntax %.* causes the expansion of the variable to be truncated starting with the right most dot (.). Thus abc.def becomes just abc.

1 Like