Tuesday, April 23, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  4] [ 0]  / answers: 1 / hits: 2257  / 2 Years ago, sat, june 25, 2022, 7:03:16

I am trying to create a simple script which will resize images. Here it is:



#!/bin/bash
echo "Script executed from: ${PWD}"

#copy image and resize it
OUTPUT_IMG="newimg.png"
PATH="${PWD}/${OUTPUT_IMG}"

cp "$1" ${OUTPUT_IMG}
mogrify -resize 400x300 ${PATH}


I am calling script with 1 parameter (image to be resized)



script thisImage.png


But I get error cp command not found and mogrify command not found.



All this works without a script meaning that I have installed all these apps.



Any ideas?


More From » bash

 Answers
2

The variable PATH has a predefined meaning: it's the search path for programs. When you type a command name, the shell (or any other program that you tell to execute this command) looks for an executable file in one of the directories mentioned in the PATH variable. In your script, cp is searched in a subdirectory called newimg.png of the current directory (which doesn't even exist, let alone contain an executable file called cp.



Use a different variable name in your script. By convention, environment variables that have a meaning to programs are usually in all uppercase. For variables that are local to a script, you can use lowercase letters to avoid clashes (variable names are case-insensitive). Better, use a more significant name (because having variables that only differ in case is confusing to humans).



#!/bin/bash
echo "Script executed from: ${PWD}"

#copy image and resize it
output_image_name="newimg.png"
output_image_path="${PWD}/${OUTPUT_IMG}"

cp "$1" "$output_image_name"
mogrify -resize 400x300 "$output_image_path"


There's no reason to sometimes use the file name and sometimes the full path here though. Furthermore, instead of copying the file then modifying it in place with mogrify, you might as well use convert directly — convert is the same as mogrify except that it writes to a different output file.



#!/bin/bash
output_image="newimg.png"
convert -resize 400x300 "$1" "$output_image"

[#27500] Monday, June 27, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
biryanrownies

Total Points: 396
Total Questions: 90
Total Answers: 106

Location: Saint Lucia
Member since Sun, Sep 5, 2021
3 Years ago
biryanrownies questions
Wed, Sep 7, 22, 18:13, 2 Years ago
Fri, Dec 3, 21, 02:50, 2 Years ago
Sat, Feb 12, 22, 16:02, 2 Years ago
Sat, Apr 15, 23, 09:22, 1 Year ago
;