One command to create and change directory - linux

I'm searching for just one command — nothing with && or | — that creates a directory and then immediately changes your current directory to the newly-created directory. (This is a question someone got for his exams of "linux-usage", he made a new command that did that, but that didn't give him the points.) This is on a debian server if that matters.

I believe you are looking for this:
mkdir project1 && cd "$_"

define a bash function for that purpose in your $HOME/.bashrc e.g.
function mkdcd () {
mkdir "$1" && cd "$1"
}
then type mkdcd foodir in your interactive shell
So stricto sensu, what you want to achieve is impossible without a shell function containing some && (or at least a ; ) ... In other words, the purpose of the exercise was to make you understand why functions (or aliases) are useful in a shell....
PS it should be a function, not a script (if it was a script, the cd would affect only the [sub-] shell running the script, not the interactive parent shell); it is impossible to make a single command or executable (not a shell function) which would change the directory of the invoking interactive parent shell (because each process has its own current directory, and you can only change the current directory of your own process, not of the invoking shell process).
PPS. In Posix shells you should remove the functionkeyword, and have the first line be mkdcd() {

For oh-my-zsh users: take 'directory_name'
Reference: Official oh-my-zsh github wiki

Putting the following into your .bash_profile (or equivalent) will give you a mkcd command that'll do what you need:
# mkdir, cd into it
mkcd () {
mkdir -p "$*"
cd "$*"
}
This article explains it in more detail

I don't think this is possible but to all people wondering what is the easiest way to do that (that I know of) which doesn't require you to create your own script is:
mkdir /myNewDir/
cd !$
This way you don't need to write the name of the new directory twice.
!$ retrieves the last ($) argument of the last command (!).
(There are more useful shortcuts like that, like !!, !* or !startOfACommandInHistory. Search on the net for more information)
Sadly mkdir /myNewDir/ && cd !$ doesn't work: it retrieves the last of argument of the previous command, not the last one of the mkdir command.

Maybe I'm not fully understanding the question, but
>mkdir temp ; cd temp
makes the temp directory and then changes into that directory.

mkdir temp ; cd temp ; mv ../temp ../myname
You can alias like this:
alias mkcd 'mkdir temp ; cd temp ; mv ../temp ../'

You did not say if you want to name the directory yourself.
cd `mktemp -d`
Will create a temp directory and change into it.

Maybe you can use some shell script.
First line in shell script will create the directory and second line will change to created directory.

Related

Directory structure variations in bash script

I have a shell script myautoappupgrade.sh where I automate a process of application upgrade. The script has to be run on few different servers. Unfortunately, the application is located in slightly different directory on each server - the number for parent directory varies between 1-20. How I can modify the script, so that the directory can be replaced by some sort of variable? I don't want to edit the script for each server because there are many directory queries in the automation script.
example:
cd /ae1/apps/myapp/upgradefiles/
unzip file.zip
./install.sh
the directory slightly changes on another server:
cd /ae2/apps/myapp/upgradefiles/
unzip file.zip
./install.sh
and another..
cd /ae3/apps/myapp/upgradefiles/
unzip file.zip
./install.sh
Try something like this:
#!/bin/bash
num=$1
cd /ae${num}/apps/myapp/upgradefiles/file.zip
unzip file.zip
./install.sh
Then call the script with the number as first argument:
myautoappupgrade.sh 1
The simple and obvious solution is to not hard-code the directory at all. Modify the script so it accepts the parent directory as an argument, or just cd into the parent directory before running the script.
Perhaps something like this:
while read server dir; do
ssh "$server" "cd '$dir' && unzip apps/myapp/upgradefiles/file.zip/file.zip && ./install.sh"
done <<\:
ernie /ae1
bert /ae2
cookiemonster /home/cmonster/anN
:
It would probably be even better if you unzipped into a temporary directory, but hopefully this should get you moving in the right direction.
Of course, if you can be sure that /ae[0-1] is always there and there is only one match,
cd /ae[0-9]/apps/myapp/upgradefiles/file.zip
would do what you are asking.
(Do you really have a file named file.zip inside a directory also named file.zip? I'm guessing actually take away the file.zip from the end of the cd path.)
By simply using:
cd /ae*/apps/myapp/upgradefiles/
The * will expand any character.

How to create folder and cd into it with one command

I'm looking for a command that would create a directory and bring me to it directly after, similar to:
$ mkdir project-one-business-dev-2
$ cd project-one-business-dev-2
I don't want to type the project's name twice because it's too long (I know I can use tab, but what if there are similar names?). Maybe only one command can do it.
A process can't change the working directory of it's parent process. That makes it impossible for an external command like mkdir to set the working directory of the calling shell to the newly created folder.
But you can create a bash function for that purpose. Put this for example into your .bashrc:
mkcd() {
mkdir -p "${1}"
cd "${1}"
}
You can do it like this:
mkdir project-one-business-dev-2 && cd "$_"
for more information check out this post on AskUbuntu

on the "local" toolchain in linux

long time lurker first time poster.
I've looked everywhere and I'm sure it's easily found but I couldn't properly word the search.
I working on some coding exercises from a textbook and I've got all my work in directories with the following hierarchy:
r00t
/ \
tools code
\
chapts
In the tools directory are a couple scripts to make my life easier. What I want, and the reason I'm posting, is to be able to call the scripts in r00t/tools wherever I am, as long as I'm inside r00t. I know I could just add them to the global PATH but that seems lazy and I don't want my PATH to balloon any more (is this even sensible?).
So, can I add scripts or programs to the "local PATH" inside the dir somehow?
Take a look over here towards the ondir (link) program letting you execute scripts upon entering or leaving directories.
With that you could dynamically change your path variable. I must however admit to never have used the program nor to be informed about its development status.
Alternatively you could replace your cd command with a script checking pwd versus your r00t directory and updating $PATH based on the outcome. of course your cd will be slowed down but probably not even noticeably.
an example:
#!/bin/bash
#alternative cd
cd $*
#check for r00t directory
if [ "$( pwd | grep -o 'r00t')" == "r00t" ] ; then
#check path variable:
if [ "$(echo $PATH | grep -o 'r00t')" != "r00t" ] ; then
export PATH=$PATH:/DIR/r00t/bin
fi
else
#remove r00t from PATH when not in r00t
if [ "$(echo $PATH | grep -o 'r00t')" == "r00t" ] ; then
export PATH=$( echo $PATH | sed 's~:/DIR/r00t/bin~~' )
fi
fi
note that now you'll have to intoduce the alias as follows:
alias cd='. ./path/to/script/alternative_cd.sh'
as the exported PATH needs to be sourced in order to work for your current shell (if using bash alternative_cd.sh, you'd only get the new PATH for the subshell the script is run in)
I tested it and it seemed to be working. Have fun.
The usual way to handle this is to put an rc file in the root directory of each of your project directory trees. In this case, r00t. Call the file r00trc or make your own naming convention.
The rc file should include an identifying change to the command line prompt in order to remind you constantly what environment the shell is using, and a re-assignment of the PATH variable to suite the needs of the project, and any other project-specific environment variables, aliases or color setting that you need.
From your default login environment, spawn a sub-shell by running 'bash' either before or after or without changing the current working directory to r00t and then source the r00trc file. This provides you with a Bash shell with the project environment and an identifying prompt. Use exit to exit the sub-shell and return to your default environment.
Avoid the temptation to collect your project rc files in your home directory or anywhere other than the root of the project directories so that they do not get lost when you tar up a project and archive it or send it to a colleague.

Change directory to path of parent/calling script in bash

I have dozens of scripts, all in different directories. (exported/expanded Talend jobs)
At this moment each job has 1 or 2 scripts, starting with the same lines, most important one:
CD ***path-to-script***
and several lines to set the Java path and start the job.
I want to create a script, which will be ran from all these scripts.
e.g.:
/scripts/talend.sh
And in all talend scripts, the first line will run /scripts/talend.sh, some examples of where these scripts are ran from:
/talend-job1_0.1/talend-job1_0.1/talend-job1/talend-job1.sh
/talend-task2_0.1/talend-task2_0.1/talend-task2/talend-task2.sh
/talend-job3_0.1/talend-job3_0.1/talend-job3/talend-job3.sh
How can I determine where the /scripts/talend.sh is started from, so I can CD to that path from within /scripts/talend.sh.
The Talend scripts are not run from within the directory itself, but from a cronjob, or a different users home directory.
EDIT:
The question was marked as duplicate, but Getting the source directory of a Bash script from within is not answering my question 100%.
Problem is:
- The basic script is being called from different scripts
- Those different scripts can be run from command line, with, and with or without a symbolic link.
- The $0, the $BASH_SOURCE and the pwd all do some things, but no solution mentioned covers all the difficulties.
Example:
/scripts/talend.sh
In this script I want to configure the $PATH and $HOME_PATH of Java, and CD to the place where the Talend job is placed. (It's a package, so that script MUST be run from that location).
Paths to the jobs are, for example:
/u/talend/talendjob1/sub../../talendjob1.sh
/u/talend/talendjob2/sub../../talendjob2.sh
/u/talend/talendjob3/sub../../talendjob3.sh
Multiple jobs are run from a TMS application. This application cannot run these scripts with the whol name (to long, name can only be 6 long), so in a different location I have symbolic links:
/u/tms/links/p00001 -> /u/talend/talendjob1/sub../../talendjob1.sh
/u/tms/links/p00002 -> /u/talend/talendjob1/sub../../talendjob2.sh
/u/tms/links/p00003 -> /u/talend/talendjob1/sub../../talendjob3.sh
/u/tms/links/p00004 -> /u/talend/talendjob1/sub../../talendjob4.sh
I think you get an overview of the complexity and why I want only one basic talend script, where I can leave all basic stuff. But I only can do that, if I know the source of the Talend script, because there I have to be to start that talend job.
These answers (beyond the first) are specific to Linux, but should be very robust there -- working with directory names containing spaces, literal newlines, wildcard characters, etc.
To change to your own source directory (a FAQ covered elsewhere):
cd "$(basename "$BASH_SOURCE")"
To change to your parent process's current directory:
cd "/proc/$PPID/cwd"
If you want to change to the directory passed as the first command-line argument to your parent process:
{ IFS= read -r -d '' _ && IFS= read -r -d '' argv1; } <"/proc/$PPID/cmdline"
cd "$argv1"
That said, personally, I'd just export the job directory to the environment variable in the parent process, and read that environment variable in the children. Much, much simpler, more portable, more accurate, and compliant with best process.
You can store pwd in a variable and then cd to it when you want to go back
This works for me:
In
/scripts/talend.sh
do
cd ${1%/*}
${1%/*} will strip off everything after the last / effectively providing a dirname for $1, which is the path to the script that calls this one.
and than call the script with the line:
/scripts/talend.sh $0.
Calling the script with $0 passes the name of the current script as an argument to the child which as shown above can be used to cd to the correct directory.
When you source /scripts/talend.sh the current directory is unchanged:
The scripts
# cat /scripts/talend.sh
echo "Talend: $(pwd)"
# cat /talend-job1_0.1/talend-job1_0.1/talend-job1/talend-job1.sh
echo Job1
. /scripts/talend.sh
Executing job1
# cd /talend-job1_0.1/talend-job1_0.1
# talend-job1/talend-job1.sh
Job1
Talend: /talend-job1_0.1/talend-job1_0.1
When you want to see the dir where the calling script is in, see get dir of script.
EDIT:
When you want to have the path of the callling script (talend-job1.sh) without having to cd to that dir first, you should get the dir of the script (see link above) and source talend.sh:
# cat /scripts/talend.sh
cd "$( dirname "${BASH_SOURCE[0]}" )"
echo "Talend: $(pwd)"
In talend.sh get the name of the calling script and then the directory:
parent_cmd=$(ps -o args= $PPID)
set -- $parent_cmd
parent_cmd=$(dirname $2)
Update: as pointed by Charles Duffy in the comments below this will cause havoc when used with paths containing white-space or glob patterns.
If procfs is available you could read the content of /proc/$PPID/cmdline or if portability is a concern do a better parsing of the args.
In /scripts/talend.sh:
cd "$(dirname "$0")"
Or:
cd "$(dirname "$BASH_SOURCE")"
Another one is:
cd "$(dirname "$_")"
#This must be the first line of your script after the shebang line
#Otherwise don't use it
Note: The most reliable of the above is $BASH_SOURCE

How to run a Linux shell command from a different directory without getting there?

How to run a Linux shell command from a different directory without actually getting there?
In the following, I want to run a make command, but without getting into the source code directory, i.e., from my home directory:
me#mypc:~$ ~/my/source/code/directory/make #This is wrong!
I have seen some examples which suggest as:
me#mypc:~$ cd ~/my/source/code/directory; make
But this ends up taking me into that source code directory, which I want to avoid.
There could the be the other option:
me#mypc:~$ cd ~/my/source/code/directory; make; cd ~
But it becomes complicated in cese.
I am wondering if there could be some way nicer and simpler than these?
You can try:
me#mypc:~$ (cd ~/my/source/code/directory; make)
Parentheses tell your shell to spawn a separate subshell, with its own current directory, and run the commands inside that subshell. After the command finishes, the subshell is closed, and you're back to your main shell, whose current directory never changed.
Do it in a subshell, e.g.
(cd ~/my/source/code/directory; make)
Alternately, you can use make's -C option, e.g.
make -C ~/my/source/code/directory
You can also use
pushd ~/my/source/code/directory; make; popd
or
current=`pwd`; cd ~/my/source/code/directory; make; cd "$current"
$ (cd directory && make)
You need to use && instead of ;. Consider something like
cd junk && rm -rf *
With &&, bash will abort if the directory junk does not exist. If you try cd junk; rm -rf * and junk doesn’t exist, you’ll delete everything in the current directory :(

Resources