1

I have obtained a bunch of files for a program as follows:

/work/xiaofenglu/science/myten.*.dump.gz

Now, I need to extract the string myten.* for the base name of sequential output files. I use the following command to process this problem:

for inputfile in *.dump.gz
do
   base_name='basename ${inputfile} .dump.gz'
done

However, it did not work.

0

1 Answer 1

1

Use parameter expansions:

#!/bin/bash

shopt -s nullglob

for f in /work/xiaofenglu/science/myten.*.dump.gz; do
    base_name=${f%.dump.gz} # removes trailing .dump.gz
    base_name=${base_name##*/} # removes everything up to last / found
    printf 'Base name is: %s\n' "$base_name"
done

Your command doesn't work since you're not even calling the command basename. You're just defining the string base_name as the verbatim string

basename ${inputfile} .dump.gz

because of the single quotes. Maybe you saw somewhere this command:

base_name=`basename ${inputfile} .dump.gz`

and you confused the backticks ` with the single quote '. With backticks instead of single quotes, the command works. But it's much better to use, instead of backticks, the $(...) construct:

base_name=$(basename "$inputfile" .dump.gz)

which is called a Command Substitution.

But I would say it's useless to call the external process basename to perform something that Bash can do very well on its own.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't know how to put a single backtick in a post... is it even possible?
single bck-quote : ` yep, just escape with single backslash.
@shellter: thanks… but it's not in “code” format… it's already better than nothing :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.