Linux setting working directory

How do I run a program with a different working directory from current, from Linux shell?

Using a Linux shell, how do I start a program with a different working directory from the current working directory? For example, I have a binary file helloworld that creates the file hello-world.txt in the current directory.

This file is inside of directory /a . Currently, I am in the directory /b . I want to start my program running ../a/helloworld and get the hello-world.txt somewhere in a third directory /c .

I discovered the hard way that su resets the working directory to the home directory of user you specify before running any -c commands. This was very helpful to me.

It’s been 12 years since I’ve posted this question and today I looked it up myself, cause I could not recall how to do that.

It’s one thing to come back to a SO post with a:visited link and an upvote already on it. It’s another thing when you’re the asker, or even the answerer. There should be a badge for that. «Forgetful»

11 Answers 11

Call the program like this:

The parentheses cause a sub-shell to be spawned. This sub-shell then changes its working directory to /c , then executes helloworld from /a . After the program exits, the sub-shell terminates, returning you to your prompt of the parent shell, in the directory you started from.

Error handling: To avoid running the program without having changed the directory, e.g. when having misspelled /c , make the execution of helloworld conditional:

Reducing memory usage: To avoid having the subshell waste memory while hello world executes, call helloworld via exec:

[Thanks to Josh and Juliano for giving tips on improving this answer!]

the entire () construct will have the exitcode of the last command inside. You can check that either directly through chaining or by inspecting $? .

Similar to David Schmitt’s answer, plus Josh’s suggestion, but doesn’t leave a shell process running:

This way is more similar to how you usually run commands on the shell. To see the practical difference, you have to run ps ef from another shell with each solution.

Just say it here — exec replaces the shell process with the given command, without creating a new process.

An option which doesn’t require a subshell and is built in to bash

$ pwd /home/abhijit $ pushd /tmp # directory changed $ pwd /tmp $ popd $ pwd /home/abhijit 

A similar suggestion has been done below by Sahil. It does not work if the command fails. Consider pushd SOME_PATH && run_stuff && popd — if run_stuff fails, than popd is not going to be executed.

Late reply, that depends on the settings of the bash file. Bash can continue executing commands even after a failed command (unlike using &&), but it can be set to not do that using set -e in the file and then it would fail to popd .

Читайте также:  Remote connect windows to linux

Still, I think pushd «$» && run_stuff; popd is better than the current answer, since the pushd/popd semantics were specifically designed for this situation of going into some directory and then coming back to the original one.

I think you’d need to write a shell script to which you would pass the parameter that would execute the series of commands as you can’t pass a parameter in the middle of an alias. If you need help writing that, you should ask a separate question and reference this one. Once you have the shell script, you could write an alias to call your new script.

Just change the last «&&» into «;» and it will cd back no matter if the command fails or succeeds:

I always think UNIX tools should be written as filters, read input from stdin and write output to stdout. If possible you could change your helloworld binary to write the contents of the text file to stdout rather than a specific file. That way you can use the shell to write your file anywhere.

$ cd ~/b $ ~/a/helloworld > ~/c/helloworld.txt 

cd SOME_PATH && run_some_command && cd —

the last ‘cd’ command will take you back to the last pwd directory. This should work on all *nix systems.

One way to do that is to create a wrapper shell script.

The shell script would change the current directory to /c, then run /a/helloworld. Once the shell script exits, the current directory reverts back to /b.

Here’s a bash shell script example:

If you always want it to go to /C, use an absolute path when you write the file.

The following worked for my simple need to set up an alias to which I can append an argument, without having to put the instructions in a function; worked in Bash and ZSH:

$ CWD=/your/target/dir command args 

My use case: I have a shell script named run-service that resolves paths to other files based on its own location. If I call it with cd ~/Code/company/scripts && run-service dev/some-service , it will expect to find a config file in ~/Code/company/services/dev/some-service . So instead of always having to cd into the directory and calling the script, I just did this:

# Alias definition alias run-service="CWD=/your/target/dir run-service" # Calling the alias $ run-service foo 

It’s probably too simplistic to be of general use, but it works for my basic use-case.

Источник

How to Use the Linux cd Command to Change Directory

Many Linux commands, such as the ls command, affect the current working directory. The current working directory is the directory your terminal window or command prompt is working in.

Linux treats the Home directory as the default working directory. Using the cd command in Linux allows you to change the current working directory.

In this tutorial, we will explain the cd command syntax and show examples of how you can use it.

How to use the Linux cd command to change directory

  • A system running a Linux distribution.
  • A user account with sudo privileges.
  • Access to the terminal window or command line.

Linux CD Command Syntax

The cd command in Linux uses the following syntax:

  • cd : Invokes the cd command.
  • [options] : Adding options changes the way the command executes.
  • [directory] : Path to the directory you want to move into.

For instance, to move to the Desktop directory, run:

If the command executes successfully, the current working directory is indicated in the terminal interface:

Читайте также:  Linux повтор команды каждые

Path to the current working directory

If the terminal interface does not indicate the current working directory, using the pwd command displays it as the output:

Using the pwd command to show the current working directory

The cd command uses the following options:

  • -L : Force following symbolic links. This option is enabled by default.
  • -P : Do not follow symbolic links. This option resolves the symbolic link to determine the parent directory before moving to the user-requested directory.
  • -e : Exit with a non-zero status if using the -P option and the command cannot resolve the symbolic link.
  • -@ : Present a file with extended attributes as a directory containing the file attributes.

How to use Linux CD Command

The Linux cd command offers several ways to navigate and change the working directory using the terminal window. It lets you change directories using relative and absolute paths, move to parent or root directories, or find directories with incomplete names.

Note: The cd command is a built-in shell command. This means that its behavior varies slightly between shells since it uses shell environment variables. Learn more in our guide to environment variables in Linux.

Changing Directory

To change to a new working directory, use the cd command with a directory path.

For instance, moving to Example_Directory, located in the Home directory:

Using the cd command to change the current working directory

Change Directory and List Content

Append the ls command to the cd command using the && flag to change to a new directory and list its content simultaneously.

Using the previous example:

Using a combination of cd and ls command to change to a new working directory and list its contents

Note: Add ls command options to change the way directory contents are displayed.

Changing Directory Using an Absolute Path

Using an absolute path to the directory means that the path starts from the root directory. For instance, changing to the Downloads directory using its absolute path:

cd /home/phoenixnap/Downloads

Changing to a new working directory using the absolute path

Changing Directory Using a Relative Path

A relative path is a path to a directory relative to the current working directory. A relative path is best used when changing to a subdirectory of the current working directory.

In the example above, the Downloads directory is a subdirectory of Home. In this case, a relative path is a result of omitting the path to the current directory from the path to the new working directory:

Changing to a new working directory using the relative path

Since the path to the current directory is /home/phoenixnap, omitting that part of the absolute path to the Downloads directory (/home/phoenixnap/Downloads) results in a relative path (Downloads).

Changing to the Previous Directory

Adding a dash symbol ( ) to the cd command returns the shell to the previous working directory. For instance, after moving from Downloads to Example_Directory, return to Downloads with:

Changing back to the previous working directory

Changing to Parent Directory

To change to the parent of the current directory, add two period symbols ( .. ) to the cd command.

For example, to move from Example01 to its parent directory Example_Directory:

Changing to the parent of the current working directory

Changing to the Root Directory

Add the slash symbol ( / ) to the cd command to move into the system’s working directory:

Changing to the system root directory

Changing Back to the Home Directory

In Linux, the Home directory represents the default working directory. Using the cd command without any options or path changes back to the default working directory:

The absence of the current working directory path indicates that you are in the default working directory:

Changing back to the default working directory

Another way to do this is to add the tilde symbol ( ~ ) to the cd command:

Changing to Another User’s Home Directory

Change to another user’s Home directory by adding the tilde symbol ( ~ ) appended with the appropriate username.

Читайте также:  Sparkle для linux установка

For instance, changing to the Home directory of a user named alex:

Changing to another user

Changing to a Directory with Spaces in the Name

If the directory name contains blank spaces, change to it by surrounding the name with single quotation marks ( ‘ ‘ ). Alternatively, append a backslash symbol ( \ ) to every word in the name except the last one:

cd 'Directory name with blank spaces' cd Directory\ name\ with\ blank\ spaces 

For example, changing to a directory named This is a directory:

cd 'This is a directory' cd This\ is\ a\ directory 

Changing to a directory with blank spaces in the name

Autocomplete Directory Name

If you don’t know the name of the directory you are trying to move to, the Linux terminal offers an autocomplete feature. After you start typing the directory name, press the Tab button on your keyboard to get autocomplete suggestions.

For instance, if you know that the name of the directory starts with an X (for instance, XYZ), type:

After reading this tutorial, you should be able to use the Linux cd command to navigate and change the current working directory in the terminal window.

Learn more about other Linux commands in our Linux commands cheat sheet.

Источник

How can I create a directory and change my working directory to the new directory?

If you really want it to be just one command, I suggest adding something like this to your .bashrc :

Entering md foo on the command line will then create a directory called foo and cd into it immediately afterwards. Please keep in mind, that you will have to reload your .bashrc for the changes to take effect (i.e. open a new console, or run source ~/.bashrc ).

mkdir «NewDirectory» && cd «NewDirectory»

  • The part behind the && will only execute if the 1st command succeeds.
  • It is called a Lists of Commands in the Bash manual.
  • There is also a shorthand version:
$ false && echo "yes" $ true && echo "yes" yes 

mkdir «NewDir» && cd «$_» works great than mkdir «NewDir» && cd «NewDir» as auto complete doesn’t work. BTW what is «$_» ?

More than that it would be quite handy if we can attach a switch to mkdir to change to new directory created.

@TheKojuEffect $_ see gnu.org/software/bash/manual/bashref.html#Lists Regarding that last one: nobody is stopping you from using an alias or a function inside .bashrc 😉

There’s no built-in function for that, but you can use shell functionality to help you not have to type the argument of the cd command again after running mkdir :

  • Type cd , then Esc . (or Alt + . ) to insert the last argument from the previous command.
  • cd !$ executes cd on the last argument of the previous command.
  • Press Up to recall the previous command line, then edit it to change mkdir into cd .

You can define a simple make-and-change-directory function in your ~/.bashrc :

Reload your .bashrc ( . ~/.bashrc ) or restart bash, and now you can type mkcd new-directory .

This simple version fails in some unusual cases involving weird directory names or .. and symbolic links. Here’s one that does. For explanations, see the Unix & Linux version of this question.

mkcd () < case "$1" in /*) mkdir -p "$1" && cd "$1";; */../*) (cd "./$/.." && mkdir -p "./$") && cd "$1";; ../*) (cd .. && mkdir -p "$") && cd "$1";; *) mkdir -p "./$1" && cd "./$1";; esac > 

Источник

Оцените статью
Adblock
detector