#! Shebang
#! /bin/bash
Tell OS to use bash shell (interpreter) to run the script.
Declaring Variable
list_of_variables=("put" "like" "this")
list_of_variables+=("you" "can" "append" "more")
list_of_variables+=("even" "more" "list_of_variables+=")
If statement with environment variable
if [ "$ENABLE_DD_PROFILE" = "true" ]; then
echo "something"
fi
Print variable
The java_args[@] syntax is used to access the elements of the java_args array. The @ symbol tells Bash to expand the array, so that the individual elements of the array are passed to the Java program as arguments.
# method 1 to print all the arguments
for arg in ${java_args[@]}; do
echo $arg
done
# method 2 to print all the arguments
printf "%s\n" "${java_args[@]}"
Example of a non working java command bash shell script
#! /bin/bash
java_args=(
"-Xmx1024m" # max heap size
"-Xms512m" # min heap size
"-XX:+HeapDumpOnOutOfMemoryError"
"-XX:HeapDumpPath=./temp/heapdump"
)
if [ "$ENABLE_DD_PROFILE" = "true" ]; then
java_args+=(
"-javaagent:dd-java-agent.jar"
"-Ddd.service=<YOUR_SERVICE>"
"-Ddd.env=<YOUR_ENVIRONMENT>"
"-Ddd.version=<YOUR_VERSION>"
"-Ddd.profiling.enabled=true"
"-XX:FlightRecorderOptions=stackdepth=256"
)
fi
# if -cp and paths are placed before the javaagent, my java would not run correctly somehow.
java_args+=(
"-cp"
"lib/*"
"lib2/*"
"-jar <YOUR_SERVICE>.jar"
)
# print all the arguments
printf "%s\n" "${java_args[@]}"
# run java command
java ${java_args[@]}
Run command
You need to chmod a shell script so that it can be executed by the user. By default, a newly created file has no execute permissions, which means that it cannot be run. The chmod command is used to change the permissions of a file.
chmod +x
make the script executable.
$ export ENABLE_DD_PROFILE=true
$ chmod +x java_args.sh && ./java_args.sh
-Xmx1024m
-Xms512m
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=./temp/heapdump
-javaagent:dd-java-agent.jar
-Ddd.service=<YOUR_SERVICE>
-Ddd.env=<YOUR_ENVIRONMENT>
-Ddd.version=<YOUR_VERSION>
-Ddd.profiling.enabled=true
-XX:FlightRecorderOptions=stackdepth=256
-cp
lib/*
lib2/*
-jar <YOUR_SERVICE>.jar
Error opening zip file or JAR manifest missing : dd-java-agent.jar
Error occurred during initialization of VM
agent library failed to init: instrument
The Java error is intentional, as the main goal is to showcase my new knowledge of bash shell scripts.
Kthxbye.
Top comments (0)