-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtmp_script
More file actions
executable file
·93 lines (80 loc) · 2.66 KB
/
tmp_script
File metadata and controls
executable file
·93 lines (80 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/bash
# check command line args
# -n -- start a new temporary script (overwrite existing)
# -p -- print the current script to the terminal
# -x -- execute the script (echo the output back to caller)
# -o [path to directory] -- path to a temporary directory to use (default ~/tmp)
# -f [file name] -- file name (no path, no extension!) to use for the temporary script (default tmp.sh)
temp_dir="$HOME/tmp"
file_name="tmp.sh"
execute_script="false"
append="true"
print_script="false"
keep_environment="false"
# Function to create a new temporary script file
#create_script([path to file]) -- path is required
create_script() {
local file_path="$1"
if [ -z "$file_path" ]; then
echo "Error: create_file requires a file path." >&2
return 1
fi
echo -n '' > "$file_path"
chmod +x "$file_path" || { echo "Error: Could not set execute permissions on $file_path" >&2; return 1; }
}
while getopts "npsxd:f:" opt; do
case $opt in
n)
append="false"
;;
p)
print_script="true"
;;
s)
keep_environment="true"
;;
x)
execute_script="true"
;;
d)
temp_dir="$OPTARG"
;;
f)
file_name="$OPTARG.sh"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
echo "Usage: $0 [-n] [-x] [-o temporary_directory] [-f script_name]" >&2
;;
esac
done
shift $((OPTIND-1))
#interpret the rest of whatever is after the args, unquoted, as the contents to output in the script
script_content="$*" # Capture all remaining arguments as script content
full_path="$temp_dir/$file_name"
# Ensure the temporary directory exists
if [ ! -d "$temp_dir" ]; then
mkdir -p "$temp_dir" || { echo "Error: Could not create temporary directory $temp_dir" >&2; exit 1; }
fi
#if -n is passed or no temporary script yet exists, then create a new one
if [ "$append" = "false" -o ! -f "$full_path" ] \
|| [ "$append" = "false" -a -f "$full_path" ]; then
create_script "$full_path";
fi
# If there is script content, append it to the temporary file
if [ -n "$script_content" ]; then
echo "$script_content" >> "$full_path"
fi
# if -p was passed, or script_content is empty, print the current script
if [ "$print_script" = "true" ]; then
# read script from $full_path, echo each line from the file
while read -r line; do
echo "$line"
done < "$full_path"
fi
# If -x is passed, execute the script and print its output
if [ "$execute_script" = "true" ]; then
for line in "$(cat $full_path)"; do
if [ -n "$line" ]; then eval $line; fi;
done
fi