5

I have a bash script:

#!/bin/bash
convert "$1" -resize 50% "$2"

Instead of passing two arguments while the script is run I want to mention just the source (or input file name) and the output file name should be auto-genarated from the source file name. Something like this "$1" | cut -d'.' -f1".jpg". If the input file name was myimage.png, the output name should be myimage.jpg. .jpg should be appended to the fist part of the source file name. It should also work if the argument is: *.png. So how can I modify my script?

1
  • Does this work at the comand line: convert "*.png" -resize 50% "*.jpg" ?? I suspect you'll need a loop in that case. Commented Mar 30, 2011 at 12:15

3 Answers 3

5

The expansion ${X%pattern} removes pattern of the end of $X.

convert "$1" -resize 50% "${1%.*}.jpg"

To work on multiple files:

for filename ; do
    convert "$filename" -resize 50% "${filename%.*}.jpg"
done

This will iterate over each of the command line arguments and is shorthand for for filename in "$@". You do not need to worry about checking whether the argument is *.png - the shell will expand that for you - you will simple receive the expanded list of filenames.

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

Comments

2
convert "$1" -resize 50% "${1%.*}.jpg"

The magic is in the %.* part, which removes everything after the last dot. If your file is missing an extension, it will still work (as long as you don't have a dot anywhere else in the path).

Comments

0
OUTFILE=`echo $1|sed 's/\(.*\)\..*/\1/'`.jpg
convert "$1" -resize 50% "$OUTFILE"

1 Comment

consider using $() instead of backticks

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.