Skip to content
Bite-Sized Musings

TIL: Customized, Automated Shell Scripting

shell, code snippet, today-i-learned1 min read

Context:

Was writing a script to pull metadata from an NFT collection.

I had to write a loop that queried the API for the asset ID, which then generated JSON files in batches of 10, now prepopulated with asset IDs. These weren't in proper JSON format yet, so I had to add the array brackets at the start and end of the file. Also had to account for customization (in case we want to try querying for another NFT project).

One of the cool things I did was writing a shell script that used flagged params, like so: Ref

1while getopts n:p:a: flag
2do
3 case "${flag}" in
4 n) max_drop=${OPTARG};;
5 p) policy_id=${OPTARG};;
6 a) auth=${OPTARG};;
7 esac
8done

So the command can be run as: ./script.sh -n 10000 or ./script.sh -p <POLICY_ID> or ./script -n 4000 -p <POLICY_ID>.

Some other code snippets I found useful:

Add text to start of file

SO Answer

Linux:

1echo 'task goes here' | cat - todo.txt > temp && mv temp todo.txt
2
3sed -i '1s/^/task goes here\n/' todo.txt
4
5sed -i '1itask goes here' todo.txt

Mac OSX:

1sed -i '.bak' '1s/^/task goes here\'$'\n/g' todo.txt
2echo -e "task goes here\n$(cat todo.txt)" > todo.txt
3echo 'task goes here' | cat - todo.txt > temp && mv temp todo.txt

Deleting last character at end of file

SO Answer

1printf '%s\n' '$' 's/.$//' wq | ex somefile

Doing division with variables

SO Answer

1expr $x / $y
2echo $((x / y))
3z = $((x / y))

Using arguments in loops

SO Answer

1for i in $(eval echo {$1..$2}); do echo $i; done

Read more:

© 2022 by Bite-Sized Musings. All rights reserved.
Theme by LekoArts