Double Clicking a shell script on Mac - macos

i have a small script that runs a jar file :
#!/bin/bash
prefix="foo";
name=`ls ${prefix}*.jar`;
echo $name;
java -jar $name prop1.properties prop2.properties
when i run it in the terminal using ./myscript.sh, it works fine and the jar file executes, but when i rename it in myscript.command and double click it, i have this error :
ls: foo*.jar : No such file or directory
I saw that apparently a .command file opens a terminal at the root directory, so I tried finding the directory containing myscript.command using that :
dir = 'find <dir> -maxdepth 1 -type d -name '*myDirContainingJar*' -print -quit'
cd $dir
but dir is just blank, any ideas ???

Opening a shell script from Finder on macOS (whether it has extension .command or is an extension-less executable shell script) makes the current user's home directory the current directory (as of macOS 10.12).
To explicitly change to the directory in which the script itself is located in a bash script, use:
cd -- "$(dirname -- "$BASH_SOURCE")"
In this invocation scenario, the following POSIX-compliant variation, which uses $0 in lieu of $BASH_SOURCE, would work too: cd -- "$(dirname -- "$0")"
Note:
Generally, if your script is invoked via a symlink and you want to change to the target's directory (the actual script file's directory as opposed to the directory in which the symlink is located), more work is needed - see this answer of mine.
When opening a script from Finder, however, this issue does not apply, because Finder itself resolves a symlink to its (ultimate) target and then invokes the target directly.

The problem with your script is that it runs with a different working directory than you tested it with. When you do ls something in a script, the script looks in the current working directory (where you cded last in case you're in a terminal), not in the directory the script is in. In general, when writing scripts like this you should use the full path of the file you're referring to or figure out the directory of the script and point to the file relative to that. One solution works in Bash, but it might not in the shell you're using.

Related

Shell Script - opening files from a different directory

I am trying to cd to a different directory by using a path to open a file, but it fails to load correctly.
I am in the directory of ~/Dev/.../Examples to run a ./test.sh script.
Inside the shell script, I have the following:
#!/bin/bash
path = '~/Datasets/foo'
....
"path"/bar
The Dataset folder is right after cd ~/
I have tried $HOME instead of ~, but it still fails to load the respective file.
Here is a code to open the bar directory with nautilus (ubuntu's explorer):
#!/bin/bash
path='/home/your_user_name/foo'
nautilus $path/bar/
Rules:
Use absolute path: /home/your_user_name/, not ~/ nor $HOME.
Bash doesn't like spaces: path='~/Datasets/foo', and not path = '~/Datasets/foo'

Change directory in bash script in windows

How can I change my working directory in bash script in windows. I have
~dp0 = C:\test\docker\windows and I want to change my directory to C:\test\build
So it means 2 levels up and then int o build folder
Thanks
Since C:\ is mounted by default into /mnt/c this will work.
Create a .bashrc in your home path by following command:
echo "BUILDDIR=/mnt/c/test/build" >> ~/.bashrc;source ~/.bashrc
cd $BUILDDIR
# Do your work below for example ./configure.
./configure
On my system in Git bash the C:\ root is just /c/ and other dirs from there are whatever they are, so it would be cd /c/test/build/.
You could also still say cd ../../build/.
Good luck.
To change the directory using a bash script is just like you would using normal bash.
cd "C:/test/build"
echo "You're now in the folder, do what you will."
Save the file as .sh and it can be used as such.
Note, when navigation your folders using a bash script remember the directory you'll be starting from is always the home directory.

Script location execution

I've been working on a script but always with a fixed directory (/opt/mw/script).
I need to change that to be able to execute the script from any directory.
I think I will need to add a "." at the beginning of the line to be able to execute the script?
For example ./mw/script
Is this correct?
Thanks
You already can execute that script from any directory with that absolute file path. It's the relative file paths (that start with ./ or ../) that can only be executed from a specific directory.
You need to add the "." if the script is in the current directory (e.g. ./script), but it is optional if the script is already inside another directory (e.g. mw/script).
Also notice that if your script contains relative references to other files and directories, you may need to use this trick to properly refer to them from any directory.
For instance, consider the following script using absolute paths:
#!/bin/bash
# lists all files in this directory
ls /opt/mw
If it is converted to relative paths as follows:
#!/bin/bash
# lists all files in this directory
ls mw
Then this script will only work if you run it from its own directory (e.g. cd /opt/ && ./script).
But then you can generalize it like this:
#!/bin/bash
SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
# lists all files in this directory
ls $SCRIPT_DIR/mw
Now the script works even when executed from another directory.

How can I cd to an alias directory in the Mac OSX terminal

Is there a way to get into an alias directory from shell with the command "cd" ? It always returns that "htdocs" isn't a directory.
Edit: I made the shortcut with the OS GUI -> rightclicked the htdocs directory and chose "Alias..." (i'm using a german OS if it's not alias maybe it's called shortcut in english?) then i moved it to my home directory (because my terminal starts from there when i open it).
All i want is to open my terminal and type "cd htdocs" so that i can work from there.
you can make symbolic link to it.
ln -s EXISTING_PATH LINK_NAME
e.g.
ln -s ~/Documents/books ~/Desktop/
Reference
Enter into a directory through an alias in Mac OS X terminal
All i want is to open my terminal and type cd htdocs so that i can work from there.
The easier approach is probably to ignore the links and add the parent directory of your htdocs directory to the CDPATH environment variable. bash(1) will check the contents of the CDPATH environment variable when you type cd foo to find the foo directory in one of the directories listed. This will work no matter what your current working directory is, and it'll be easier than setting symbolic links.
If the path to your htdocs is located /srv/www/htdocs/, then you could use CDPATH=/srv/www. Then, cd foo would first look for /srv/www/foo/ and change to it if it exists; if not, then it would look for foo in the current working directory and change to it if it exists. (This might get confusing if you have multiple htdocs directories on your system; in that case, CDPATH=.:/srv/www would let you change into a child directory easily but still use the /srv/www/htdocs/ version if no ./htdocs directory is present.)
You can add the CDPATH=/srv/www line to your ~/.bashrc file so it works every time you start a terminal.
I personally use this to quickly work in the directory which is present deep inside one of my Volumes in my Mac.
Open your ~/.bash_profile, create an alias to the directory by adding this:
alias cdh="cd /Volumes/Haiku/haiku/src/apps/superprefs"
Save it, restart your terminal. Now on typing cdh in your terminal should change the working directory to the one mentioned as the alias.
I am not sure how OSX exposes Alias links but since you are using bash you can just create a variable in your .bashrc file.
On its own line put:
htdocs=YourDirectoryPath/
Once you have restarted bash you can just type cd $htdocs
There is a old hint on macworld to do this in a way that is integrated with BASH: Enable 'cd' into directory aliases from the Terminal
Plus, here is an answer that uses this solution on superuser.
You may be able to use osascript to do this -- this command seems to work:
cd "`osascript -e "on run aFile" -e "set aFile to POSIX file aFile as alias" -e "tell application "\""Finder"\"" to return POSIX path of ( ( original item of aFile ) as text ) " -e "end run" path_to_my_Finder_alias 2>/dev/null`"
Basically this command is running an AppleScript that finds the destination path of the argument (path_to_my_Finder_alias) in a subshell, then wraps it in double quotes, and changes the directory to it.
Maybe someone with a little more bash expertise can turn it into a bash alias or function.
try:
alias cdgo=`echo cd /root/go/`
cdgo will run, then get command "cd /root/go/" and enter, and it will change your directory in current terminal process
It works on my centos, no test with osx

How to make a shell script global?

I am on Mac's OS 10.6, and I am trying to learn a thing or two about shell scripting. I understand how to save a shell script and make it executable, but I am wondering what I can do or where I can save the file to make it global (that is, accessible no matter what folder I am in).
For example, if I save a .sh file in the /Users/username/ directory and make it executable, I can only execute that script in that specific directory. If I navigate to /Users/username/Downloads, for example, I can't execute the script.
Also, any suggestions of resources for learning more about shell scripting would be helpful. Thanks
/usr/local/bin would be the most appropriate location. Mac OS X has it in the PATH by default
There are two ways to do it -
Put your script in usr/local/bin and make sure it is executable(chmod +x my_script)(This is already set in the path, you can check by doing an echo $PATH)
Create a folder in your home directory called bin. (For your personal scripts)
cd ~ (Takes you to your home directory)
mkdir bin (create a bin folder)
vim .bash_profile (to set path environment variable)
export PATH=~/bin:$PATH (Press i then add this line and then do esc and type :wq)
Now you can just type the name of your script and run it from anywhere you want.
** NOTE: If you want to run the script with a shortened command rather than typing your entire filename, add the following to your .bash_profile:
alias myscript='my_script.sh'
Then you can run the script by simply typing myscript. (you can sub in whatever alias you'd like)
Traditionally, such scripts either go in ~/bin (ie: the bin directory in your home directory) or /usr/local/bin/ The former means the script will only work for you, the latter is for scripts you want anybody on the system to be able to run.
If you put it in ~/bin, you may need to add that to your PATH environment variable. /usr/local/bin should already be on the path.
In mac operating system
Open bash ~/.bashrc file.
add path of your script in your bashrc file , using
export PATH="$PATH:/Users/sher.mohammad/Office/practice/practiceShell"
Open your ~./bash_profile file and add [[ -s ~/.bashrc ]] && source ~/.bashrc
open new terminal window
Now whenever you will open your terminal your script will be loaded
This one is super easy if you are familiar with your bashrc file! This will entirely use just your .bashrc file and takes 2 seconds to accomplish.
(I use Arch Linux Manjaro so I use .bashrc located in my home directory)
The code to be placed in your .bashrc file:
# Simple bashrc method to launch anything in terminal from any directory
YOURCOMMAND () {
cd /path/to/directory/containing/your/script/ && ./YOURSCRIPT
}
As you can see, first you use the simple 'cd' command and give it the directory of the scripts location, then use '&&' so that you can make the next command executed right after, and finally open your script just as you would normally! Super easy and saved right in your .bash file! :)
Hope I've helped someone!
Sincerely,
AnonymousX
On using bash shell, write that script as function and then put it to the .bashrc or source the file which containing that function by "source file_name"
Now execute the script by function call in the shell.
Either saving it in /usr/bin (or any other directory present in PATH) or editing PATH to include the directory you saved it in will basically make it run in any directory.
from the working directory of 'script.sh'" mv [script.sh] /usr/local/bin"( not tested but seems to be the least complex way IMO.)
You should put it in the global executable directory on your machine. I think that would usually be /usr/bin on Unix-based operating systems (this would however most often require super user privileges on that machine).
You could also put it in any other directory that is in the $PATH environment variable, although it would only work for those users who have that directory in that variable.
You can find the value of $PATH by typing echo $PATH in a shell. The directories are separated by :.

Resources