1

I am new to bash scripting, so if I ask anything stupid sorry for it xD

I'm making a script which run come cli commands everyday. The output which I get from the cli command is a ID which I have to use that same next day. So its like

cli-command-delete $oldid; # here we delete the old id which was generated past day

newid=$(cli-command-create) #here we get the new id.

Now I want to save the newid to oldid, which will be used next day or next time when the script will run. How can I save it as a env variable & replace that value after new id is created? If vm reboots, will that value be saved? I saw on google to use export, but I'm confused how to save it on other name

2 Answers 2

1

"If vm reboots, will that value be saved" -- No.

Write it to a file instead.

id_file=$HOME/.local/data/cli-command.id

# delete the old one
cli-command-delete "$(<"$id_file")"

# save the new one
cli-command-create > "$id_file"
0

You have to save it to some some permanent storage such as file and read it when the script starts and ideally check if it could be read. For example:

#!/usr/bin/env sh

id_path=~/.id

oldid="$(cat $id_path)"

if [ -z "$oldid" ]
then
    printf "Failed to read oldid from %s\n" "$id_path" >&2
    exit 1
fi

cli-command-delete "$oldid"; # here we delete the old id which was generated past day

cli-command-create > "$id_path"
1
  • 1
    Thanks you very much I opted this method :)
    – ph3ro
    Sep 21 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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