Issue
I am writing a function in a Posix shell script that compresses files if an env variable is set to true, then that file is pushed to a remote location. Instead of just compressing one global file, how would I pass any number of files to be compressed as parameters to the function? Below is my code:
CODE:
#!/bin/sh
COMPRESSION=true
FILE="test.json"
LOG_FILE="test.log"
compress_file() {
gzip $FILE
stat $FILE.gz
if [ $? -eq 0 ]; then
FILE=$FILE.gz
else
FILE=$FILE
fi
}
push_file() {
FILE=$1
cmd() {
STORAGE_URL="https://somepath"
TIMESTAMP=$(date -u '+%a, %d %b %Y %T GMT')
if [ "$COMPRESSION" = true ]; then
compress_file
CONTENT_TYPE="'content-type: application/gzip'"
else
CONTENT_TYPE="'content-type: application/json'"
fi
curl --fail --silent --show-error -X PUT -T $FILE -H $CONTENT_TYPE -H 'x-ms-version: 2020-02-10' -H "x-ms-date: $TIMESTAMP" "$STORAGE_URL"
}
}
push_file()
Say for example I wanted to compress both $FILE
and $LOG_FILE
, or one and not the other. Or, any number of files for that matter.
Solution
You would stop using global variables
compress_file() {
local file
for file in "$@"; do
gzip "$file"
done
}
and call the function like
compress_file "$FILE" "$LOG_FILE"
All the arguments to a function (aka positional parameters) live in the "$@"
array-like variable
Answered By - glenn jackman