-1

I'm studying about how to use 'cut'.

#!/bin/bash

for file in *.c; do
    name = `$file | cut -d'.' -f1`
    gcc $file -o $name
done

What's wrong with the following code?

  • `for file in 'ls *.c' do` ?? – Reda Meskali May 15 '18 at 19:37
  • `echo $file` into the `cut`. – Perette May 15 '18 at 19:50
  • 1
    Possible duplicate of [How can remove the extension of a filename in a shell script?](https://stackoverflow.com/questions/12152626/how-can-remove-the-extension-of-a-filename-in-a-shell-script) – Benjamin W. May 15 '18 at 19:59
  • Also see [How to use Shellcheck](https://github.com/koalaman/shellcheck), [How to debug a bash script?](https://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](https://stackoverflow.com/q/951336/608639) (SO), [How to debug bash script?](https://askubuntu.com/q/21136) (AskU), [Debugging Bash scripts](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html), etc. – jww May 15 '18 at 22:57

2 Answers2

-1

There are a number of problems on this line:

name = `$file | cut -d'.' -f1`

First, to assign a shell variable, there should be no whitespace around the assignment operator:

name=`$file | cut -d'.' -f1`

Secondly, you want to pass $file to cut as a string, but what you're actually doing is trying to run $file as if it were an executable program (which it may very well be, but that's beside the point). Instead, use echo or shell redirection to pass it:

name=`echo $file | cut -d. -f1`

Or:

name=`cut -d. -f1 <<< $file`

I would actually recommend that you approach it slightly differently. Your solution will break if you get a file like foo.bar.c. Instead, you can use shell expansion to strip off the trailing extension:

name=${file%.c}

Or you can use the basename utility:

name=`basename $file .c`
mwp
  • 8,217
  • 20
  • 26
-1

You should use the command substitution (https://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution) to execute a command in a script.

With this the code will look like this

#!/bin/bash

for file in *.c; do
    name=$(echo "$file" | cut -f 1 -d '.')
    gcc $file -o $name
done
  1. With the echo will send the $file to the standard output.
  2. Then the pipe will trigger after the command.
  3. The cut command with the . delimiter will split the file name and will keep the first part.
  4. This is assigned to the name variable.

Hope this answer helps