Linux what is tilda

Meaning of tilde in Linux bash (not home directory)

First off, I know that ~/ is the home directory. CDing to ~ or ~/ takes me to the home directory. However, cd ~X takes me to a special place, where X seems to be anything. In bash, if I hit » cd ~ » and hit tab, it shows a bunch of possible ~X options like ~mail and ~postgres and ~ssh . Going to those folders and doing a pwd shows me that these folders are not in the home directory; they’re all over the place. They are not aliases. I’ve checked. They’re not env. variables, or else they’d require a $ . What is setting these links, and where can I find where these are being set?

~X simply returns the literal «~X» but ~ returns $HOME and ~+ returns $PWD — they are not special other than that they fetch shell variables. i.e. they do not store the values or execute a command to look them up. They are already defined. Have you tried ~- ? I can’t think of a use for it, but again, it returns a shell variable $OLDPWD

8 Answers 8

It’s a Bash feature called «tilde expansion». It’s a function of the shell, not the OS. You’ll get different behavior with csh, for example.

To answer your question about where the information comes from: your home directory comes from the variable $HOME (no matter what you store there), while other user’s homes are retrieved real-time using getpwent() . This function is usually controlled by NSS; so by default values are pulled out of /etc/passwd , though it can be configured to retrieve the information using any source desired, such as NIS, LDAP or an SQL database.

Tilde expansion is more than home directory lookup. Here’s a summary:

~ $HOME ~fred (freds home dir) ~+ $PWD (your current working directory) ~- $OLDPWD (your previous directory) ~1 `dirs +1` ~2 `dirs +2` ~-1 `dirs -1` 

dirs and ~1 , ~-1 , etc., are used in conjunction with pushd and popd .

Edited to add:

As Sean Bright pointed out in a comment, the baseline tilde behavior regarding home directories is codified as standard behavior for POSIX-compliant shells. Additionally, the wordexp() C API function is specified to implement this behavior. Though, obviously, use with caution.

~+ is roughly the same as . However, to use something like ./file it has to go to the file system and figure out where . is located — it takes a few cycles. Using ~+ saves it the work by simply returning the contents of the shell variable $PWD which is already defined as you traverse the file system.

Читайте также:  Установка криптопро линукс минт

The ~ and ~username forms are specified by POSIX, so it’s not specifically a bash thing. It may have been added to POSIX since this answer was written though.

@SeanBright Fair enough; my point was that it was a shell thing, and different shells do different things. And other non-shell things (like GUIs or other programs) may do nothing at all. POSIX, after all, is just a standard saying «please implement these features in your stuff.» But you’re right, it’s worth pointing out the standards involved.

Those are the home directories of the users. Try cd ~(your username) , for example.

Best answer in my case. Also, in my particular case, it was the root directory/folder, not the home folder.

Are they the home directories of users in /etc/passwd ? Services like postgres, sendmail, apache, etc., create system users that have home directories just like normal users.

Those are users. Check your /etc/passwd .

cd ~username takes you to that user’s home directory.

FTW. Upvote. TNX for clearing that up. I wonder how many cycles and perhaps even a subshell are involved in that one. Just imagine if your system has 3K users, like at a small ISP. Yikes.

On my machine, because of the way I have things set up, doing:

cd ~ # /work1/jleffler cd ~jleffler # /u/jleffler 

The first pays attention to the value of environment variable $HOME ; I deliberately set my $HOME to a local file system instead of an NFS-mounted file system. The second reads from the password file (approximately; NIS complicates things a bit) and finds that the password file says my home directory is /u/jleffler and changes to that directory.

The annoying stuff is that most software behaves as above (and the POSIX specification for the shell requires this behaviour). I use some software (and I don’t have much choice about using it) that treats the information from the password file as the current value of $HOME, which is wrong.

Applying this to the question — as others have pointed out, ‘ cd ~x ‘ goes to the home directory of user ‘x’, and more generally, whenever tilde expansion is done, ~x means the home directory of user ‘x’ (and it is an error if user ‘x’ does not exist).

Читайте также:  Int to string in linux

It might be worth mentioning that:

cd ~- # Change to previous directory ($OLDPWD) cd ~+ # Change to current directory ($PWD) 

I can’t immediately find a use for ‘ ~+ ‘, unless you do some weird stuff with moving symlinks in the path leading to the current directory.

Источник

Что такое Тильда в Linux

Тильда (~) — это метасимвол в Linux, который имеет особое значение в пределах оболочки терминала. Это «ярлык» Linux, который используется для представления домашнего каталога пользователя. Тильда (~) показывает домашнюю папку пользователя в текущем каталоге. Пользователь может вводить команды типа cd/ в командной строке. Эта команда изменяет каталог на корневую папку.

Если вы когда-нибудь сталкивались с тильдой, но не знаете, как ее использовать, это руководство для вас. В этом руководстве мы дадим вам краткую информацию о тильде в Linux с соответствующими примерами.

Что такое Тильда в Linux?

В этом разделе мы будем использовать несколько примеров, чтобы вы могли понять все о тильде в Linux.

Пример 1:
Давайте начнем с базового примера, где мы хотим использовать «Документы» в качестве текущего рабочего каталога в терминале. Сначала выполните следующую команду, указав полное расположение каталога:

cd /home/user/Загрузки

С другой стороны, мы также можем выполнить следующую команду, используя только тильду (~) вместе с косой чертой (/), чтобы найти каталог «Документы»:

компакт-диск ~/Документы

Запуск обеих предыдущих команд в терминале дает одинаковый результат. Однако тильда заменила местоположение каталога, то есть /home/user, чтобы обеспечить тот же результат.

Пример 2:

Давайте используем команду echo с тильдой, чтобы напечатать путь к вашему домашнему каталогу. Давайте запустим следующую команду, чтобы получить результаты:

Вы можете использовать следующую команду для получения информации о других пользователях:

Это совершенно очевидно, но если вы хотите узнать имя текущего рабочего каталога, вы можете использовать следующую команду:

Наконец, мы можем использовать тильду только для получения информации о пользователе и каталоге.

Следовательно, это доказывает, что тильда в Linux является продвинутой заменой каталога /home/user.

Вывод

Тильда (~) в Linux используется в качестве замены каталога /home/user при смене текущего рабочего каталога в терминале. В этом руководстве мы включили все возможные детали, связанные с символом тильды в Linux. Мы также объяснили, что такое тильда (~) и как ее использовать в терминале Linux. Тильда — это простая альтернатива, которая может сэкономить ваше время при работе в Linux. Надеюсь, это руководство помогло вам узнать больше о тильде в Linux.

Источник

What is Tilde in Linux

Tilde (~) is a meta character in Linux that has a special meaning within the confines of the terminal’s shell. It is a Linux “shortcut” that is used to represent the user’s home directory. Tilde (~) shows the user’s home folder of the current directory. The user can type commands like cd/ at the command prompt. This command changes the directory to the root folder.

Читайте также:  Serviio pro лицензия linux

If you ever come across tilde but don’t know how to use it, this guide is for you. In this guide, we will give you a brief information on tilde in Linux with the appropriate examples.

What is Tilde in Linux?

In this section, we will use multiple examples so that you can understand everything about tilde in Linux.

Example 1:
Let’s start with the basic example where we want to use the “Documents” as the current working directory in the terminal. First, execute the following command having the complete location of the directory:

cd /home/user/Downloads

On the other side, we can also execute the following command by only using tilde (~) along the slash (/) to locate the “Documents” directory:

cd ~/Documents

Running both the previous commands in the terminal gives the same output. However, tilde has replaced the directory location, i.e. /home/user, to provide the same result.

Example 2:

Let’s use the echo command with tilde to print the path of your home directory. Let’s run the following command to get the results:

You can use the following command to get the information about the other users:

It’s quite obvious, but if you want to know the name of the current working directory, you can use the following command:

Finally, we can only use tilde to get the information about the user and the directory.

Hence, it proves that tilde in Linux is an advanced substitute for the /home/user directory.

Conclusion

A tilde (~) in Linux is used as a replacement for the /home/user directory while changing the current working directory in the terminal. In this guide, we included every possible detail related to the tilde symbol in Linux. We also explained what tilde (~) is and how to use it in a Linux terminal. Tilde is a simple alternative that can save up your time while working on Linux. Hopefully, this guide helped you learn more about tilde in Linux.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.

Источник

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