Why does it work this way?
Hello, so, it seems to me that an uninitialized variable is substituted with command line arguments, am I missing something, and why, why, why does it work this way?
cat >wtf
#!/bin/bash
for x
do
echo $x
done
Executing:
wtf runge kutta
Gives this result:
runge
kutta
Just as a proof of concept.
https://redd.it/122osie
@r_bash
Hello, so, it seems to me that an uninitialized variable is substituted with command line arguments, am I missing something, and why, why, why does it work this way?
cat >wtf
#!/bin/bash
for x
do
echo $x
done
Executing:
wtf runge kutta
Gives this result:
runge
kutta
Just as a proof of concept.
https://redd.it/122osie
@r_bash
Reddit
r/bash on Reddit: Why does it work this way?
Posted by u/McUsrII - No votes and 2 comments
Getting Context of a Loop in an Interactive Shell?
Apparently, zsh has the %_ prompt expansion variable which expands to, for example "for" if you are in the middle of writing a for loop, "dquote" if you are writing a continuation of a line using double quotes and you haven't closed it, and is useful in PS2 prompts. I was unable to find an equivalent in bash, so I'm trying to figure out a different way to determine that. My goal is to dynamically set PS2 so I know at a glance why I am getting a secondary prompt, so if I'm in an interactive shell, I want to see something like:
for i in {1..3}; do
for> # rest of my loop
for> done
I've tried using an alias for
https://redd.it/122zrx1
@r_bash
Apparently, zsh has the %_ prompt expansion variable which expands to, for example "for" if you are in the middle of writing a for loop, "dquote" if you are writing a continuation of a line using double quotes and you haven't closed it, and is useful in PS2 prompts. I was unable to find an equivalent in bash, so I'm trying to figure out a different way to determine that. My goal is to dynamically set PS2 so I know at a glance why I am getting a secondary prompt, so if I'm in an interactive shell, I want to see something like:
for i in {1..3}; do
for> # rest of my loop
for> done
I've tried using an alias for
for, a function, and a function to be used as a trap handler for DEBUG, nothing worked and I can't think of any other methods. Was hoping someone might have some other ideas. EDIT: I've also tried using history, but if there is a way to do it that way, I haven't figured it out.https://redd.it/122zrx1
@r_bash
Reddit
r/bash on Reddit: Getting Context of a Loop in an Interactive Shell?
Posted by u/brown_panick - No votes and no comments
ChatGPT Created a Bash Monster and I Need Help
Hi, all.
I have a large amount of data in 2 folders that I need to merge. Each folder has multiple files/folders in it. If the source folder doesn't exist in the destination, I want to move (not copy) it to the destination folder and move on. If it does exist, I need to check the contents of the folder against the destination and move everything that doesn't exist. If something exists, overwrite it with whatever is in the source. This should only leave duplicates in the source folder, and then we can delete them.
I wrote a very specific set of instructions and fed them to ChatGPT and built off of what I had. The code below seems to work except for the fact that it isn't deleting a folder although the log file says it did delete it.
I have zero bash noscripting experience and haven't coded anything in about 20 years so I'm a bit lost.
Any ideas as to what I can change to accomplish what I need?
Any help is greatly appreciated - thanks in advance!
​
​
​
​
​
https://redd.it/123buum
@r_bash
Hi, all.
I have a large amount of data in 2 folders that I need to merge. Each folder has multiple files/folders in it. If the source folder doesn't exist in the destination, I want to move (not copy) it to the destination folder and move on. If it does exist, I need to check the contents of the folder against the destination and move everything that doesn't exist. If something exists, overwrite it with whatever is in the source. This should only leave duplicates in the source folder, and then we can delete them.
I wrote a very specific set of instructions and fed them to ChatGPT and built off of what I had. The code below seems to work except for the fact that it isn't deleting a folder although the log file says it did delete it.
I have zero bash noscripting experience and haven't coded anything in about 20 years so I'm a bit lost.
Any ideas as to what I can change to accomplish what I need?
Any help is greatly appreciated - thanks in advance!
#!/bin/bash​
# Set source and destination folder pathssrc_folder="/path/to/source/folder"dest_folder="/path/to/destination/folder"​
# Set log file pathlog_file="/path/to/logfile.log"​
# Function to log messages to the log filelog() {echo "$(date): $1" >> "$log_file"}​
# Function to traverse directories and move/copy filestraverse_dir() {for file in "$1"/*; doif [ -d "$file" ]; then# If the file is a directory, create the directory in the destination if it doesn't existif [ ! -d "${2}/${file#$1/}" ]; thenmkdir -p "${2}/${file#$1/}"log "Created directory ${2}/${file#$1/}"fi# Traverse the directory recursivelytraverse_dir "$file" "${2}/${file#$1/}"# After traversing the directory, remove the directory from the sourcermdir "$file" 2>/dev/nulllog "Removed directory $file from source folder"# Check if the parent directory is empty and remove it if it isparent="$(dirname "$file")"rmdir "$parent" 2>/dev/nulllog "Removed directory $parent from source folder"elif [ -f "$file" ]; then# If the file is a regular file, check to see if it's the same in both foldersif cmp -s "$file" "${2}/${file#$1/}"; then# If the files are the same, delete the file from sourcerm "$file"log "Deleted file $file from source folder"else# If the files are different, copy/move the file to destinationcp -f "$file" "${2}/${file#$1/}"log "Copied file $file to ${2}/${file#$1/}"rm "$file"log "Deleted file $file from source folder"fifidone# Check if the source directory is empty and remove it if it isrmdir "$1" 2>/dev/nulllog "Removed directory $1 from source folder"}​
# Check if source folder exists in destination folderif [ ! -d "${dest_folder}/${src_folder##*/}" ]; then# If it does not, move entire folder to destinationmv "$src_folder" "$dest_folder"log "Moved folder $src_folder to $dest_folder"else# If it does, traverse the source folder and move/copy filestraverse_dir "$src_folder" "${dest_folder}/${src_folder##*/}"# After traversing the source folder, remove the source folder if it is emptyrmdir "$src_folder" 2>/dev/nulllog "Removed source folder $src_folder"fihttps://redd.it/123buum
@r_bash
Reddit
r/bash on Reddit: ChatGPT Created a Bash Monster and I Need Help
Posted by u/blockhead_76 - No votes and no comments
man-sections: Lets you peruse the different sections of f.x man bash trough fzf and batcat.
Usage:
man-sections COMMAND
man-sections takes a command as parameter
It will then let you choose which section you want to read
from the section list. Again and again, until you hit 'q'.
man-sections:
#!/bin/bash
set -o pipefail
set -e
if [ $# -lt 1 ] ; then
echo "${0##/} : I need a command to show the \
sections of a man page from.\nTerminating..." >&2
exit 2
fi
curs_off() {
COF='\e[?25l' #Cursor Off
printf "$COF"
}
curs_on() {
CON='\e[?25h' #Cursor On
printf "$CON"
}
clear_stdin()
(
old_tty_settings=`stty -g`
stty -icanon min 0 time 0
while read none; do :; done
stty "$old_tty_settings"
)
sections() {
man "$1" | sed -nE -e '/^[A-Z][A-Z]+[ ]/p' | sed -n -e '3,$p' | sed '$d'
}
showsection() {
echo -e "$1\n\n$2\n"
man "$1" | sed -nE -e '/'"$2"'/,/^[A-Z][A-Z]+[ ]*/ {
/'"$2"'/{p;n}
/^[A-Z][A-Z]+[ ]*/{q}
p
}
'
}
cursoff
stty -echo
# turns off the keyboard echo and cursor.
trap 'stty sane ; curson ' EXIT TERM INT
echo -e "\e[1;30mPress 'q' to quit, any key to continue...\e[0m" >&2
while true ; do
wanted="$(sections "$1" | fzf --with-nth 1 --ansi --no-preview \
--preview-window='up:0%')"
if [[ -n "$wanted" ]] ; then
showsection $1 "$wanted" | batcat -l manpage
else
exit
fi
clearstdin
read -s -r -N 1 input
if [[ "${input^^}" == "Q" ]] ; then
exit
fi
done
stty echo
curson
https://redd.it/123nlfc
@r_bash
Usage:
man-sections COMMAND
man-sections takes a command as parameter
It will then let you choose which section you want to read
from the section list. Again and again, until you hit 'q'.
man-sections:
#!/bin/bash
set -o pipefail
set -e
if [ $# -lt 1 ] ; then
echo "${0##/} : I need a command to show the \
sections of a man page from.\nTerminating..." >&2
exit 2
fi
curs_off() {
COF='\e[?25l' #Cursor Off
printf "$COF"
}
curs_on() {
CON='\e[?25h' #Cursor On
printf "$CON"
}
clear_stdin()
(
old_tty_settings=`stty -g`
stty -icanon min 0 time 0
while read none; do :; done
stty "$old_tty_settings"
)
sections() {
man "$1" | sed -nE -e '/^[A-Z][A-Z]+[ ]/p' | sed -n -e '3,$p' | sed '$d'
}
showsection() {
echo -e "$1\n\n$2\n"
man "$1" | sed -nE -e '/'"$2"'/,/^[A-Z][A-Z]+[ ]*/ {
/'"$2"'/{p;n}
/^[A-Z][A-Z]+[ ]*/{q}
p
}
'
}
cursoff
stty -echo
# turns off the keyboard echo and cursor.
trap 'stty sane ; curson ' EXIT TERM INT
echo -e "\e[1;30mPress 'q' to quit, any key to continue...\e[0m" >&2
while true ; do
wanted="$(sections "$1" | fzf --with-nth 1 --ansi --no-preview \
--preview-window='up:0%')"
if [[ -n "$wanted" ]] ; then
showsection $1 "$wanted" | batcat -l manpage
else
exit
fi
clearstdin
read -s -r -N 1 input
if [[ "${input^^}" == "Q" ]] ; then
exit
fi
done
stty echo
curson
https://redd.it/123nlfc
@r_bash
Reddit
r/bash on Reddit: man-sections: Lets you peruse the different sections of f.x man bash trough fzf and batcat.
Posted by u/McUsrII - No votes and no comments
Hey guyz!! I upgraded the bash noscript for termux app added battery function and some improvements Any ideas on self update the noscript on upcoming updates that i made...
https://redd.it/123scy0
@r_bash
https://redd.it/123scy0
@r_bash
Reddit
r/bash on Reddit: Hey guyz!! I upgraded the bash noscript for termux app added battery function and some improvements Any ideas on…
Posted by u/A_J07 - No votes and 3 comments
Need leetcode like questions + solution
Hey guys i need leet code like questions+solution or any questions+solution from basic to advanced in bash noscripting for practice.
https://redd.it/123ui7s
@r_bash
Hey guys i need leet code like questions+solution or any questions+solution from basic to advanced in bash noscripting for practice.
https://redd.it/123ui7s
@r_bash
Reddit
r/bash on Reddit: Need leetcode like questions + solution
Posted by u/Minute_Ad5775 - No votes and no comments
run bash noscript on remote server, I want the output on the local machine
Hi all,
I am trying to build a bash noscript that will go to a remote server within out domain. The noscript will run different small noscripts base on the selection the user makes from a case block of code. EG:
do a df -h, uptime and say cat /etc/fstab file. But I would like the output to display on the screen of the server I am working from. I have seen different ways, but none has worked for me. I have also seen the use of Localhost but not sure how this one works. Any links or feedback would be appreciated. thanks
https://redd.it/1242t11
@r_bash
Hi all,
I am trying to build a bash noscript that will go to a remote server within out domain. The noscript will run different small noscripts base on the selection the user makes from a case block of code. EG:
do a df -h, uptime and say cat /etc/fstab file. But I would like the output to display on the screen of the server I am working from. I have seen different ways, but none has worked for me. I have also seen the use of Localhost but not sure how this one works. Any links or feedback would be appreciated. thanks
https://redd.it/1242t11
@r_bash
Reddit
r/bash on Reddit: run bash noscript on remote server, I want the output on the local machine
Posted by u/Individual-Self-9533 - No votes and 1 comment
Please, help me write a bootstrap noscript to display ec2 instance metadata on a web page
I am a noob when it comes to coding/noscripting. I need to write a bootstrap noscript that will display the ec2 instance ID and availability zone on my web page. So far what I have is:
\#!/bin/bash
sudo yum update
sudo yum install httpd -y
sudo systemctl start httpd
sudo systemctl enable httpd
sudo aws s3 cp s3://mybucket/index1.html /home/ec2-user/index2.html
INSTANCE-ID=curl http://169.254.169.254/latest/meta-data/instance-id
INSTANCE-AZ=curl http://169.254.169.254/latest/meta-data/placement/availability-zone
sed 's/instanceID/$INSTANCE-ID/' index2.html
sed 's/AZ/$INSTANCE-AZ/' index2.html
The curl command doesn't seem to be working, and the sed command keeps skipping over the $INSTANCE-ID part. Also, When I run the last four lines in the ec2 CLI it just echos the entire html file and only run's "sed 's/AZ/$INSTANCE-AZ/' index2.html".
Again, I'm trying to replace "instanceID" and "AZ" (Both inside of my html doc) with the values of $INSTANCE-ID and $INSTANCE-AZ (from my bootstrap noscript INSTANCE-ID=curl..., INSTANCE-AZ=curl...)
If there's a better way please let me know.
https://redd.it/1245ezx
@r_bash
I am a noob when it comes to coding/noscripting. I need to write a bootstrap noscript that will display the ec2 instance ID and availability zone on my web page. So far what I have is:
\#!/bin/bash
sudo yum update
sudo yum install httpd -y
sudo systemctl start httpd
sudo systemctl enable httpd
sudo aws s3 cp s3://mybucket/index1.html /home/ec2-user/index2.html
INSTANCE-ID=curl http://169.254.169.254/latest/meta-data/instance-id
INSTANCE-AZ=curl http://169.254.169.254/latest/meta-data/placement/availability-zone
sed 's/instanceID/$INSTANCE-ID/' index2.html
sed 's/AZ/$INSTANCE-AZ/' index2.html
The curl command doesn't seem to be working, and the sed command keeps skipping over the $INSTANCE-ID part. Also, When I run the last four lines in the ec2 CLI it just echos the entire html file and only run's "sed 's/AZ/$INSTANCE-AZ/' index2.html".
Again, I'm trying to replace "instanceID" and "AZ" (Both inside of my html doc) with the values of $INSTANCE-ID and $INSTANCE-AZ (from my bootstrap noscript INSTANCE-ID=curl..., INSTANCE-AZ=curl...)
If there's a better way please let me know.
https://redd.it/1245ezx
@r_bash
Reddit
r/bash on Reddit: Please, help me write a bootstrap noscript to display ec2 instance metadata on a web page
Posted by u/Kumdongie - No votes and 1 comment
Having a hard time incrementing a variable, can someone show where I am wrong at? Thanks
So I set a variable to a uid that I pull from a server. I then want to increment this by 1 and echo that out.
I keep gettingsyntax error: invalid arithmetic operator (error token is "
​
My code so far is as:
uid=$(kubectl command | awk) <-- ultimately returns a value such as 2000
echo "UID = ${uid}"newuid=$((uid++))echo "New uid is $uid"
Any thought why I am recieving this error? I am 100% confident I am not getting a decimal and its returning 2000.
I created the below to test and it works as expected
uid=5000
echo "UID = ${uid}"
newuid=$((uid++))
echo "New uid is $uid"
This works when I set the uid to a number in the noscript instead of pulling it in via a variable.
I feel it has something to do with a character that kubectl is returning that is not showing in the echo commands.
https://redd.it/1246xtg
@r_bash
So I set a variable to a uid that I pull from a server. I then want to increment this by 1 and echo that out.
I keep gettingsyntax error: invalid arithmetic operator (error token is "
​
My code so far is as:
uid=$(kubectl command | awk) <-- ultimately returns a value such as 2000
echo "UID = ${uid}"newuid=$((uid++))echo "New uid is $uid"
Any thought why I am recieving this error? I am 100% confident I am not getting a decimal and its returning 2000.
I created the below to test and it works as expected
uid=5000
echo "UID = ${uid}"
newuid=$((uid++))
echo "New uid is $uid"
This works when I set the uid to a number in the noscript instead of pulling it in via a variable.
I feel it has something to do with a character that kubectl is returning that is not showing in the echo commands.
https://redd.it/1246xtg
@r_bash
Reddit
r/bash on Reddit: Having a hard time incrementing a variable, can someone show where I am wrong at? Thanks
Posted by u/Interested_Minds1 - No votes and 1 comment
how to send keystrokes
how can i register any other keystroke like <ENTER> key command in bash noscript
https://redd.it/124g02n
@r_bash
how can i register any other keystroke like <ENTER> key command in bash noscript
https://redd.it/124g02n
@r_bash
Reddit
r/bash on Reddit: how to send keystrokes
Posted by u/Old_Yak1 - No votes and no comments
Need help with simple brightness noscript.
Hey there, I am new to Linux and Bash and i was making a simple noscript to get my brightness level as a percentage but i keep getting the following output:
0%
With the expected output:
50%
It is impossible that the issue lies with the cat command since I do not need root privileges to cat the file and the file includes an integer:
$ cat /sys/class/backlight/intelbacklight/brightness
530
$ cat /sys/class/backlight/intelbacklight/maxbrightness
1060
Anyways, here is my noscript:
#!/bin/bash
brightness=$(cat /sys/class/backlight/intelbacklight/brightness)
maxbrightness=$(cat /sys/class/backlight/intelbacklight/maxbrightness)
brightnesspercentage=$(($brightness/$maxbrightness*100))
echo "$brightnesspercentage%"
Thanks in advance!
https://redd.it/124hfaa
@r_bash
Hey there, I am new to Linux and Bash and i was making a simple noscript to get my brightness level as a percentage but i keep getting the following output:
0%
With the expected output:
50%
It is impossible that the issue lies with the cat command since I do not need root privileges to cat the file and the file includes an integer:
$ cat /sys/class/backlight/intelbacklight/brightness
530
$ cat /sys/class/backlight/intelbacklight/maxbrightness
1060
Anyways, here is my noscript:
#!/bin/bash
brightness=$(cat /sys/class/backlight/intelbacklight/brightness)
maxbrightness=$(cat /sys/class/backlight/intelbacklight/maxbrightness)
brightnesspercentage=$(($brightness/$maxbrightness*100))
echo "$brightnesspercentage%"
Thanks in advance!
https://redd.it/124hfaa
@r_bash
Reddit
r/bash on Reddit: Need help with simple brightness noscript.
Posted by u/7_S3M_7 - No votes and 2 comments
Bash noobie here: What is $ used for ?
I tried to run $(uname -r)
to no avail.
https://redd.it/124hf5q
@r_bash
I tried to run $(uname -r)
to no avail.
https://redd.it/124hf5q
@r_bash
Reddit
r/bash on Reddit: Bash noobie here: What is $ used for ?
Posted by u/vaultRadon - No votes and 2 comments
a chatgpt discussion
Chat gpt seems to be pretty good at bash, I think the definite preference is python but it seems to be pretty good at building skeleton noscript that you can qa and unit test.
Gives pretty good explanations too.
Just don't get it using dd, it's a partition destroying liability.
How have you found it ?
https://redd.it/124h7gj
@r_bash
Chat gpt seems to be pretty good at bash, I think the definite preference is python but it seems to be pretty good at building skeleton noscript that you can qa and unit test.
Gives pretty good explanations too.
Just don't get it using dd, it's a partition destroying liability.
How have you found it ?
https://redd.it/124h7gj
@r_bash
Reddit
r/bash on Reddit: a chatgpt discussion
Posted by u/simonmcnair - No votes and 7 comments
Why can't I use !! in bash noscripts or in the bashrc ?
Ideally I would like be able to set an alias that does the same thing as !!, or call a noscript that does the same thing as !! . However i get "command not found" . The only way I am able to repeat a command is by directly typing !! into the prompt. Is there a way to get around this ?
https://redd.it/124vjzu
@r_bash
Ideally I would like be able to set an alias that does the same thing as !!, or call a noscript that does the same thing as !! . However i get "command not found" . The only way I am able to repeat a command is by directly typing !! into the prompt. Is there a way to get around this ?
https://redd.it/124vjzu
@r_bash
Reddit
r/bash on Reddit: Why can't I use !! in bash noscripts or in the bashrc ?
Posted by u/nesteajuicebox - No votes and no comments
Trying to find hex in bin file
I'm trying to search a bin file for "1E FA 80 3E 00 B8 01 00 00 00"
I can find 1E
grep -obUaP "\x1E" "$file"
and I can find FA
grep -obUaP "\xFA" "$file"
But trying to find 2 bytes doesn't work:
grep -obUaP "\x1E\xFA" "$file"
I'm actually trying find and replace the 2 bytes that come after "1E FA 80 3E 00 B8 01 00 00 00".
https://redd.it/125d3up
@r_bash
I'm trying to search a bin file for "1E FA 80 3E 00 B8 01 00 00 00"
I can find 1E
grep -obUaP "\x1E" "$file"
and I can find FA
grep -obUaP "\xFA" "$file"
But trying to find 2 bytes doesn't work:
grep -obUaP "\x1E\xFA" "$file"
I'm actually trying find and replace the 2 bytes that come after "1E FA 80 3E 00 B8 01 00 00 00".
https://redd.it/125d3up
@r_bash
Reddit
r/bash on Reddit: Trying to find hex in bin file
Posted by u/DaveR007 - No votes and 2 comments
Why can't the shell access the ssh authentication agent launched by the noscript?
I pieced together a simple noscript that allows me to backup my Windows 10 PC (using WSL) to my NAS which is running Ubuntu. I managed to get it working but during debugging one thing I found confusing was that after the noscript ran if I wanted to add another key to ssh-agent the shell could see ssh-agent running but it couldn't interact with it. (see below for console log)
I am aware that when I launch the noscript it creases a subprocess of the current shell but why did the last command I typed fail to add the key to the authentication agent? Are processes launched in a subprocess not accessible by the shell?
​
me@grimlock:\~$ cat backup2computron.sh#!/bin/bash
me@grimlock:\~$ cat backup2computron.sh
\#!/bin/bash
​
​
if [[ -n $(pidof ssh-agent) \]\]
then
echo "ssh-agent is already running"
else
eval `ssh-agent -s`
ssh-add /home/me/.ssh/grimlock_rsa_4096
fi
​
cp /mnt/c/Users/me/AppData/Local/Google/Chrome/User\\ Data/Default/Bookmarks /mnt/c/Users/me/Documents/data/backup
rsync -haP --append-verify --no-perms --omit-dir-times --delete -e "ssh -i /home/me/.ssh/grimlock_rsa_4096" /mnt/c/Users/me/Documents/data/* me@10.0.0.1:/mnt/dataPool/data/backup/
​
me@grimlock:\~$ ./backup2computron.sh
Agent pid 839
Identity added: /home/me/.ssh/grimlock_rsa_4096 (me@grimlock)
sending incremental file list
me@grimlock:\~$ pidof ssh-agent
839
me@grimlock:\~$ ssh-add /home/me/.ssh/id_ed25519
Could not open a connection to your authentication agent.
me@grimlock:\~$
https://redd.it/125iwsh
@r_bash
I pieced together a simple noscript that allows me to backup my Windows 10 PC (using WSL) to my NAS which is running Ubuntu. I managed to get it working but during debugging one thing I found confusing was that after the noscript ran if I wanted to add another key to ssh-agent the shell could see ssh-agent running but it couldn't interact with it. (see below for console log)
I am aware that when I launch the noscript it creases a subprocess of the current shell but why did the last command I typed fail to add the key to the authentication agent? Are processes launched in a subprocess not accessible by the shell?
​
me@grimlock:\~$ cat backup2computron.sh#!/bin/bash
me@grimlock:\~$ cat backup2computron.sh
\#!/bin/bash
​
​
if [[ -n $(pidof ssh-agent) \]\]
then
echo "ssh-agent is already running"
else
eval `ssh-agent -s`
ssh-add /home/me/.ssh/grimlock_rsa_4096
fi
​
cp /mnt/c/Users/me/AppData/Local/Google/Chrome/User\\ Data/Default/Bookmarks /mnt/c/Users/me/Documents/data/backup
rsync -haP --append-verify --no-perms --omit-dir-times --delete -e "ssh -i /home/me/.ssh/grimlock_rsa_4096" /mnt/c/Users/me/Documents/data/* me@10.0.0.1:/mnt/dataPool/data/backup/
​
me@grimlock:\~$ ./backup2computron.sh
Agent pid 839
Identity added: /home/me/.ssh/grimlock_rsa_4096 (me@grimlock)
sending incremental file list
me@grimlock:\~$ pidof ssh-agent
839
me@grimlock:\~$ ssh-add /home/me/.ssh/id_ed25519
Could not open a connection to your authentication agent.
me@grimlock:\~$
https://redd.it/125iwsh
@r_bash
Writing haversine function in bash
I'm trying to convert the python haversine function [here:](https://stackoverflow.com/a/4913653)
def haversine(lon1, lat1, lon2, lat2):
# Calculate the great circle distance in kilometers between two points
# on the earth (specified in decimal degrees)
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles. Determines return value units.
return c * r
To pure bash. I know, I know, why? Just because really. Anyway I got this:
#!/bin/bash
# Haversine function implementation
# Usage: haversine lat1 lon1 lat2 lon2
# Convert degrees to radians
deg2rad() {
echo $(echo "scale=10; $1 * 0.017453292519943295" | bc -l)
}
# bc has arctan, but not arcsin so, stolen from http://advantage-bash.blogspot.com/2012/12/trignometry-calculator.html
asin() {
if (( $(echo "$1 == 1" | bc -l) ));then
echo "90"
elif (( $(echo "$1 < 1" | bc -l) ));then
echo "scale=3;a(sqrt((1/(1-($1^2)))-1))" | bc -l
elif (( $(echo "$1 > 1" | bc -l) ));then
echo "error"
fi
}
# Haversine formula
haversine() {
R=6371 # Earth radius in km
dLat=$(echo "$3 - $1" | bc -l)
dLon=$(echo "$4 - $2" | bc -l)
lat1=$(deg2rad $1)
lon1=$(deg2rad $2)
lat2=$(deg2rad $3)
lon2=$(deg2rad $4)
a=$(echo "scale=10; (s($dLat/2))^2 + c($lat1) * c($lat2) * (s($dLon/2))^2" | bc -l)
c=$(echo "scale=10; 2 * asin(sqrt($a))" | bc -l)
d=$(echo "scale=10; $R * $c" | bc -l)
echo $d
}
haversine $1 $2 $3 $4
Just some math. The problem I have when I run it with something like `haversine 22.70416 -118.29725 19.57834 -155.07947` I get an error that tells me `asin not defined` right near the end. It's defined right there, right above the haversine function. I'm not sure what it is I'm missing.
https://redd.it/125y1yk
@r_bash
I'm trying to convert the python haversine function [here:](https://stackoverflow.com/a/4913653)
def haversine(lon1, lat1, lon2, lat2):
# Calculate the great circle distance in kilometers between two points
# on the earth (specified in decimal degrees)
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles. Determines return value units.
return c * r
To pure bash. I know, I know, why? Just because really. Anyway I got this:
#!/bin/bash
# Haversine function implementation
# Usage: haversine lat1 lon1 lat2 lon2
# Convert degrees to radians
deg2rad() {
echo $(echo "scale=10; $1 * 0.017453292519943295" | bc -l)
}
# bc has arctan, but not arcsin so, stolen from http://advantage-bash.blogspot.com/2012/12/trignometry-calculator.html
asin() {
if (( $(echo "$1 == 1" | bc -l) ));then
echo "90"
elif (( $(echo "$1 < 1" | bc -l) ));then
echo "scale=3;a(sqrt((1/(1-($1^2)))-1))" | bc -l
elif (( $(echo "$1 > 1" | bc -l) ));then
echo "error"
fi
}
# Haversine formula
haversine() {
R=6371 # Earth radius in km
dLat=$(echo "$3 - $1" | bc -l)
dLon=$(echo "$4 - $2" | bc -l)
lat1=$(deg2rad $1)
lon1=$(deg2rad $2)
lat2=$(deg2rad $3)
lon2=$(deg2rad $4)
a=$(echo "scale=10; (s($dLat/2))^2 + c($lat1) * c($lat2) * (s($dLon/2))^2" | bc -l)
c=$(echo "scale=10; 2 * asin(sqrt($a))" | bc -l)
d=$(echo "scale=10; $R * $c" | bc -l)
echo $d
}
haversine $1 $2 $3 $4
Just some math. The problem I have when I run it with something like `haversine 22.70416 -118.29725 19.57834 -155.07947` I get an error that tells me `asin not defined` right near the end. It's defined right there, right above the haversine function. I'm not sure what it is I'm missing.
https://redd.it/125y1yk
@r_bash
Stack Overflow
Haversine formula in Python (bearing and distance between two GPS points)
Problem
I would like to know how to get the distance and bearing between two GPS points.
I have researched on the haversine distance. Someone told me that I could also find the bearing using the same
I would like to know how to get the distance and bearing between two GPS points.
I have researched on the haversine distance. Someone told me that I could also find the bearing using the same
program to print out biggest number from a set of numbers
i am trying to make a program to print out like:
How many numbers: 5
1
2
3
4
5
Largest number is 5
​
So my question is, do I need to use like an array method for the set of numbers
https://redd.it/1260aue
@r_bash
i am trying to make a program to print out like:
How many numbers: 5
1
2
3
4
5
Largest number is 5
​
So my question is, do I need to use like an array method for the set of numbers
https://redd.it/1260aue
@r_bash
Reddit
r/bash on Reddit: program to print out biggest number from a set of numbers
Posted by u/RoseLolxd - No votes and 2 comments
How to check in bash if python noscript is running?
I use android (termux) scheduler to trigger following scheduler.sh
#!/data/data/com.termux/files/usr/bin/bash
# load EVs
source "$HOME/storage/shared/Books/AppsCfg/Termux/envfile"
python "$MEMS/Binv/noscripts/binvscheduler.py"
Most of the time it works great (according to schedule android triggers scheduler.sh which triggers binvscheduler.py noscript), but sometimes on device wake up binvscheduler.py gets double triggered. I added create lock file logic into python noscript and it catches 99% of double triggers except one case... (i can't even understand how it's possible. maybe somehow 2 binvscheduler.py run exactly same moment so python can't create lock file fast enough. Not sure)
Anyway, how do i check inside bash (in scheduler.sh) if binvscheduler.py is already running or not?
https://redd.it/12625u0
@r_bash
I use android (termux) scheduler to trigger following scheduler.sh
#!/data/data/com.termux/files/usr/bin/bash
# load EVs
source "$HOME/storage/shared/Books/AppsCfg/Termux/envfile"
python "$MEMS/Binv/noscripts/binvscheduler.py"
Most of the time it works great (according to schedule android triggers scheduler.sh which triggers binvscheduler.py noscript), but sometimes on device wake up binvscheduler.py gets double triggered. I added create lock file logic into python noscript and it catches 99% of double triggers except one case... (i can't even understand how it's possible. maybe somehow 2 binvscheduler.py run exactly same moment so python can't create lock file fast enough. Not sure)
Anyway, how do i check inside bash (in scheduler.sh) if binvscheduler.py is already running or not?
https://redd.it/12625u0
@r_bash
Reddit
r/bash on Reddit: How to check in bash if python noscript is running?
Posted by u/rtwyyn - No votes and 1 comment