Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
for i in *.jpg
    j = '$i | cut -d . -f 1'
    convert $i $j".png"
done line 3: j: command not found

I know about mogrify, just wanted to know how to get variables done in bash.

share|improve this question
up vote 1 down vote accepted

You have to remove the spaces around =:

for i in *.jpg
    j=`echo $i | cut -d . -f 1`
    convert $i $j".png"
share|improve this answer
Oh...That was it ? Thanks. – Shabeer Naha Apr 15 '11 at 5:46
Also, j should've been j=echo $i | cut -d . -f 1 – Shabeer Naha Apr 15 '11 at 5:51
Yes, you're right. I oversaw this. I will update the answer. – bmk Apr 15 '11 at 5:53
@Shabeer: If you need to use backticks in a comment, prefix these with a backslash (\) as in j=`echo $i | cut -d . -f 1`. – Lekensteyn Apr 15 '11 at 7:52

You can also use bash's builtin parameter expansion to remove the first dot and everything after it: j="${i%%.*}"

If you want to remove the last dot and anything following it (i.e. the file's extension), use: j="${i%.*}"


$ i="file.with.dots.ext"
$ echo "${i%%.*}"
$ echo "${i%.*}"
share|improve this answer
And that's probably what he really wants. So for f in ./*.jpg; do convert "$f" "${f%.*}.png"; done. – geirha Apr 18 '11 at 7:21

In addition, your script won't work as expected if any filename contains any special character (such as a space). You should get in the habit of always enclosing variable references in double quotes. Try this:

for i in *.jpg
    j="$(echo "$i" | cut -d . -f 1)"
    convert "$i" "${j}.png"
share|improve this answer
That will throw an error, unless $i happens to hold a command name. – glenn jackman Apr 15 '11 at 10:32
Yes, it's buggy code in ways beyond the double quotes. I see now that the original reply has been edited to include backticks. So, now I have a better idea of what the OP wanted. Without those backticks, the code is incomprehensible, at least to me. I've edited my answer. – Scott Severance Apr 15 '11 at 13:07

Integrating bash parameter expansion and double quotes for files with special characters in their names, and the code simplifies too:

for f in *.jpg; do 
    convert "$f" "${f%.*}.png"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.