Команды zsh mac os

Настройка ZSH в Mac OS

Mar 22, 2017 · 1 min read

С недавних пор начал использовать Mac OS, почти сразу подумал, что стандартный терминал не очень-то и удобен.

В качестве оболочки будем использовать ZSH, о нём, думаю, не слышал только любитель красивых UI, а вместо стандартного терминала я использую iTerm2.

В Mac OS ZSH предустановлен, поэтому сразу устанавливаем его в качестве оболочки по умолчанию с помощью команды chsh -s /bin/zsh . После перезапуска терминала оболочкой должен быть уже ZSH, если попросит начать настройку, то прервём сей процесс, нажав q.

Ручками мы писать конфиги, разумеется, не будем, пусть это сделает “Oh My Szh”. Переходим в домашний каталог и выполняем:

След у ющим шагом откроем для редактирования файл

/.zshrc и изменим значение параметра ZSH_THEME на agnoster , сохраняемся и перезапускаем терминал. В этот момент вы, скорее всего, увидите криво (никак) отображаемые символы, всё это происходит из-за некоторых отсутствующих шрифтов в системе, исправим это:

  1. Скачаем архив — вот здесь .
  2. Перейдём в “ fonts-master/UbuntuMono/” и установим все шрифты в этой директории.
  3. В настройках терминала выставляем шрифт “ Ubuntu Mono derivative Powerline”.

После перезапуска терминала вы, наконец, сможете узреть нормально работающую тему “agnoster”.

Источник

Dmitriy Azarov

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

Для начала скачаем и установим альтернативу стандартному терминалу, а именно iTerm2.

По умолчанию в Mac OS установлена оболочка zsh. Это альтернатива оболчки shell по умолчанию. Следующий шаг это установка Oh My Zsh. Oh-My-Zsh это open source фреймворк, который поддерживается сообществом. Предназначен для управления настройками ZSH. Поставляется с большим количеством дополнительных функций, плагинов и тем. Для установки выполняем команду в консоли:

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

Шрифты

Устанавливаем дополнительные шрифты (Powerline Fonts). Скачиваем и выполняем install.sh

Цвета

Скачиваем тему Solarized Dark для iTerm2. Заходим в настройки iTerm2 ( Profiles > Colors > Import. ). Импортируем тему и выбираем ее из списка.

В соседней вкладке выбираем шрифты. Я выбрал Meslo .

Меняем тему в файле настроек Oh My Zsh. Выполняем команду на открытие этого файла.

Заменяем тему и добавляем настройку DEFAULT_USER (чтобы в консоле не было user@machine).

Источник

Настройка ZSH в MacOS

С началом использования MacOS, почти сразу понимаешь, что стандартный терминал не очень-то и удобен.

В качестве оболочки будем использовать ZSH, о нём, думаю, не слышал только любитель красивых UI, а вместо стандартного терминала я используем iTerm2.

В MacOS ZSH предустановлен, поэтому сразу устанавливаем его в качестве оболочки по умолчанию с помощью команды:

После перезапуска терминала оболочкой должен быть уже ZSH.

Если попросит начать настройку, то прервём сей процесс, нажав q.

Ручками не нужно переписывать конфиги, пусть это сделает Oh My Szh. Это набор плагинов и настроек, которые решают самые популярные задачи и делают ваш шелл просто супер удобным. Установим его, следуя инструкциям с официального сайта.

Переходим в домашний каталог и выполняем:

Установка прошла, но ничего не поменялось? Надо закрыть терминал и снова открыть его, чтобы настройки, которые приехали к нам из oh-my-zsh, прочитались и применились. Закрыли-открыли, теперь видим новое приветствие:

Приветствие шелла после установки Oh My ZSH

Это стандартная тема oh-my-zsh под названием robbyrussell (по имени автора). Мы можем поставить любую из тем, которые поставляются с oh-my-zsh. Я, использую Bureau.

Чтобы поменять тему, напишите её название (маленькими буквами, как на странице со списком тем) в файле .zshrc . Он лежит в вашей домашней папке ( /Users/Ваш_логин или /home/ваш_логин ). Поскольку он начинается с точки, он скрыт. Включите отображение скрытых файлов. Тему нужно прописать в переменную ZSH_THEME , это в районе восьмой строки, вот так:

Меняем тему в конфиге с помощью переменной ZSH_THEME

Сохраните файл и снова перезапустите терминал (или откройте в нём новую вкладку). Теперь шелл выглядит по-новому:

Тема Bureau в шелле

Это тема Bureau. В верхней строчке сначала имя пользователя, потом имя машины, потом путь к папке, где пользователь сейчас находится. Справа текущее время. В следующей строке просто символы, которые обозначают, что ввод здесь, а справа после шестиугольника текущая версия Node.js, ветка Git (если пользователь сейчас в Git-репозитории), и кружочки, которые обозначают, что есть несохранённые изменения. В этой теме версия Node.js показывается только если вы используете Node Version Manager.

Тема Agnoster в шелле

Если, увидите кривые символы, то не пугайтесь, всё это происходит из-за некоторых отсутствующих шрифтов в системе.

  1. Скачаем архив — вот здесь.
  2. Перейдём в “fonts-master/UbuntuMono/” и установим все шрифты в этой директории.
  3. В настройках терминала выставляем шрифт “Ubuntu Mono derivative Powerline”.

После перезапуска терминала вы, наконец, сможете узреть нормально работающий терминал.

Для правильной работы темы во встроенном терминале VScode в конфиг нужно добавить:

Источник

Zsh (Z shell on MacOS)

Apple’s heavy hand is forcing adoption of POSIX and even switch to Python

At its developer conference on June 4, 2019, Apple stated that, beginning with the Fall 2019 Catalina version of macOS, Z shell (zsh) would replace Bash as the default shell command language interpreter.

Читайте также:  Linux для huawei matebook

This article presents a deep but hopefully succinct guided tour through Z shell usage and issues.

TL;DR Summary

BTW Shells are a command line interface (CLI) that allows users to interact with the computer’s operating system by typing rather than moving a mouse on a GUI (Graphical User Interface).

PROTIP: Ignore fake news clickbait articles such as “Upcoming MacOS Catalina to Ditch Bash in Favour of Zsh” (from InfoQ), which is technicall incorrect. The Apple announcement is about the default. After the change goes into effect, Bash will still be installed and you can still change the default back to Bash.

  • Execute zsh temporarily or as default
  • zsh is better than bash/sh in several aspects
  • Bash scripts break in Zsh (due to “bashisms”)
  • Bashisms in bash scripts break in zsh, so existing bash scripts need to be migrated and tested
  • Apple’s disruption opens up a discussion about compatibility of script commands across platforms and POSIX.
  • Change the default shell back to bash
  • Switch to an alternative shell replacement FISH?
  • Exit to Python and back is perhaps the ultimate solution for cross-platform compatibile automation
  • Among shells

    First, open a Terminal on your macOS machine (on Mojave or whatever version).

    In fact, several shell programs are installed with macOS:

    Get a list of shells allowed:*

    The response (on macOS Catalina) is:

    PROTIP: The predecessor Bourne Shell can still be invoked by the sh command.

    The response on macOS Mojave:

    Why the disruption?

    Obtain the version metadata:

    The response on a machine running macOS Catalina and Mojave:

    The “GNU” in the response reminds us that bash (named as a contraction of “Bourne-Again Shell”), replaces the Bourne Shell by adding “Bashisms”.* See https://en.wikipedia.org/wiki/Bash_(Unix_shell)

    The Verge notes that “Apple is stuck using version 3.2 of bash that has been licensed under GPLv2, as newer versions are licensed under GPLv3. Apple has kept clear of using GPLv3 packages in macOS as the license is generally more restrictive to companies like Apple that sign their own code and it includes explicit patent grants, too.”

    A big reason to upgrade to Bash 4.0 (introduced February 2009) are associative arrays.

    Zsh is already in macOS

    Identify the version of zsh installed while on Mojave or earlier:

    The response if you are at Catalina version:

    The response if you are at Mojave version:

    Wikipedia says “Zsh is an extended Bourne shell with a large number of improvements, including some features of Bash, ksh, and tcsh.” (Korn shell). tcsh (“tee shell”) is the native root shell for BSD-based systems such as FreeBSD, which early versions of MacOS is based. OS X switched from tcsh to bash in version 10.3. tcsh is based on csh, the C-shell.

    macOS does not have latest Zsh

    PROTIP: The version of zsh from Apple is likely not the latest because Apple does not automatically update it (like modern browsers do).

    The latest version of Zsh available is listed in the Zsh website’s News page at

    At time of writing, it’s 5.8

    PROTIP: Zshell has been around so long that its source code repository is still on Sourceforge since its initial release in 1990, at
    https://sourceforge.net/p/zsh/code/ci/master/tree/ and
    https://sourceforge.net/projects/zsh/files

    Install latest Z Shell (zsh) using Homebrew

    PROTIP: Since one should not overwrite Apple’s stuff, upgrading requires installation of the latest version as if it did not already exist.

    PROTIP: Z shell is also called zsh becuase of the Homebrew command to install it on macOS:https://github.com/robbyrussell/oh-my-zsh/wiki/themes

    NOTE: Ignore advice to add -without-etcdir to disable the reading of Zsh rc files in /etc, which is obsolete since 2018.

    BTW, On an Ubuntu system the install command is a similar:

    PROTIP: Notice that the “mojave” in the message above means that the installation needs to be repeated with each new version of Apple macOS.

    PROTIP: Notice the “To activate these completions, add the following to your .zshrc:”

    Get information about what was installed:

    Confirm location of installation:

    Install Zsh Completions

    The response at time of writing:

    Open .bashrc where zsh-completions installed.

    Prompt settings are different

    If you type in the command while in the Bash shell:

    The response prompt can be a mess because zsh doesn’t understand prompt specifiers for Bash. For example, my

    /.bash_profile file defines a PS1 system environment variable with this specification:

    \n add a blank line and indents. For easier readability.

    \n positions the cursor always on the same spot at the left of the screen so I don’t have to search for it.

    PROTIP: Zsh spits out the PS1 variable when it can’t find the

    /.zshrc that it uses (instead of

    /.bash_profile to define prompts, paths, etc.

    Emulate Other Shells

    zsh has a built-in command to emulate different shells:

    -R restores all the options to their default values for that shell.

    Execute zsh temporarily

    To Switch to zsh (replace your current shell with a new shell):

      Command bye now exits zsh just as exit in bash.

    Similarly, to switch to Bash from inside Zsh:

    -l (for —login ) avoids a source reset.

    zsh always read , .zshrc when starting an interactive shell, whether it’s a login one or not.

    Default to Zsh

    To flip back to Bash shell:

    PROTIP: Control the look of the prompt in Bash by setting the PROMPT_COMMAND variable to one or more of the special characters will customize it for you.

    To Switch to bash (replace your current shell with a new shell):

    Читайте также:  Mac os как скрывать файлы

    Similarly, to switch to Bash from inside Zsh:

    Identify where shells are installed:

    You would see this if zsh was installed in a way that requires sudo to change:

    In Terminal, select Preferences > General > Shells open to change to:

    Close and start your Terminals for changes to take.

    chsh to make zsh the default

    PROTIP: Some tutorials recommend using a command such as “chsh -s /bin/zsh”. But my recommendation is instead of a hard-coded path, have the command look up where zsh is located. This is because there can be multiple versions of zsh around.

    Use the chsh command:

    You would be prompted “Password for …”, so give it up.

    Alternately, there is an approach which directly updates the Mac’s user db, without need to edit /etc/shells, is the dscl (Directory Services Command Utility) also used to create new users, reset password, etc. from the command line rather than the GUI. (see the dscl man page).

    Verify the system variable that defines the shell your system defined:

    If you have Z shell, it would be:

    PROTIP: The concern is making Z shell the default, not whether to install it.

    Verify the switch

    Verify the process running:

    If you have Bash, it would return:

    If you have Z shell, it would return:

    Why Z shell is better than Bash

    Here is a small list of advantages to using zsh.

    Automatic cd: Just type the name of the directory anywhere in the path (you don’t need to specify the entire path)

    Recursive path expansion: For example “/u/lo/b” expands to “/usr/local/bin”

    Spelling correction and approximate completion: If you make a minor mistake typing a directory name, ZSH fixes it for you

    Z shell is case insensitive.

    Floating point support (Bash does not have)

    Hash data structures support (requires upgrade to Bash 4)

    File globbing in Z uses character patterns that are similar, but not identical to those used in regexps. Example: “He said his name was [KC]arl” to (express ambiguity). See https://www.linuxnix.com/10-file-globbing-examples-linux-unix

    To display all available options for a command, along with a short description, type the command followed by -, then hit tab. Tab through to select the option shown.

    Zsh comes with commands that need to be installed in Bash:*:

    Startup/shutdown scripts zshenv , zprofile , zshrc , zlogin , and zlogout

    zcalc is a command-line calculator for doing quick calculations without leaving the terminal. (Load it with autoload -Uz zcalc and run with zcalc)

    zparseopts parses complex options (arguments) provided to shell scripts

    zmv does massive file/directory renames. To append ‘.txt’ to every file name run:

    • Z comes with an auto-update tool that makes it easier to keep installed plug-ins and themes updated.

    See a list of Z Shell built-in commands in the Zsh Manual at:

    More opinions about zsh:

    Script Bashisms break in Zsh

    PROTIP: Unlike Microsoft Windows which selects the program to execute a file based on the file name extension, Linux looks into the first line within the file. That line which is called a “Shebang”. Thus, shell scripts do not require a file extension, but many add one anyway, such as thisfile.sh .

    In a script, if you use Bashisms, have this she-bang:

    By contrast, the recommended way to call python is:

    PROTIP: The use of env takes a bit longer because it goes out and finds the program rather than specifying the program “bash” in a certain path:

    The problem with the above location is that it is not available in other platforms and thus makes the script non-portable.

    Alternately, to ensure your script runs on the widest variety of systems:

    This is because the sh interpreter is POSIX compliant. Bash is not.

    BTW In Ubuntu, the default shell was changed from bash (the GNU Bourne-Again Shell), then to /bin/sh, then to dash (the Debian Almquist Shell) in Ubuntu 6.10. That’s back when actual Bourne shell and Korn shell weren’t open-source at that time. * Dash is faster to start than bash.

    There is also a Debian Posh shell, Busybox shell, etc.

    There are also other distributions, such as Cygwin (emulator in Windows), MinGW(used in git bash), CentOS, Amazon Linux, Red Hat, Debian, etc.

    Each flavor of shell has a different algorithm for deciding which startup script to run.

    The big issue of concern is compatibility with other Linux distributions. A further shift to MacOS’s FreeBSD roots would add “cognitive overload”. because the vast majority of other CLI ecosystems remain on Bash. Constantly thinking about whether one needs to use Z shell or Bash shell disrupts the “muscle memory” of developers, and thus reduce productivity.

    Cloud shells on cloud vendors use Bash

    • Azure Cloud Shell https://shell.azure.com/
    • Google
    • Amazon
    • etc.

    One can configure Windows 10 to use Z shell but many use git bash which remains in Bash.

    Some find Apple’s move exciting because Apple is leading the rest of the tech world into the future, like Apple did about removing 3.5 mm headphone jacks on iPhone X.

    So the transition will be painful, as the dream of one shell script that runs across operating systems is now dashed.

    Z Shell plug-ins

    meaning in your $HOME directory) is one file that enables and disables plugins. For example:

    WARNING: Adding plugins cause your shell startup time to increase.

    The sequence is important. “prompt” must come last. history-substring-search must come before it, and syntax-highlighting must come before that.*

    Z shell Prompts

    Zsh has several built-in advanced prompts.*

    Start Zsh advanced prompt support with

    autoload -U promptinit , then promptinit

    Читайте также:  Windows 10 update assistant error

    List available prompt names with prompt -l .

    Display all available prompts with prompt -p .

    Except for the list and display commands above, insert the other ones in

    /.zshrc to be automatically executed at shell start, with the prompt you chose.

    Z shell themes

    The powerlevel9k theme adds a right-aligned info box, integration with git and command history, incredible customization, and wraps it all up in a slick interface based on the powerline plugin for vim.

    Enable it in .zshrc:

    Customize the default prompt by defining POWERLEVEL9K_LEFT_PROMPT_ELEMENTS in your .zshrc. For example, to define a minimal prompt:

    Read documentation at https://github.com/bhilburn/powerlevel9k#customizing-prompt-segments

    Based on https://www.howtogeek.com/362409/what-is-zsh-and-why-should-you-use-it-instead-of-bash/

    Other themes for Z shell:

    Bashisms against portability

    “Bashisms” are shell syntax which is only understood by the bash shell and not other shells.

    To enable a shell script to run on more platforms, convert use of “bashisms” to POSIX: https://en.wikipedia.org/wiki/POSIX#POSIX.2

    Replace function funcname() with funcname()

    TODO: To verify, run linter shellcheck.

    On Debian, it’s shipped as part of the package maintainer tools.

    If you use the Atom text editor, install the plug-in for checkbashisms.

    Configure a Git pre-commit hook to run https://tracker.debian.org/pkg/devscripts

    Some of Bash’s scripting features are derived from the ksh and predecessor shells rather than those defined by POSIX standard defined by the IEEE at http://pubs.opengroup.org/onlinepubs/009695399/nfindex.html. The shell standard 1003.1-2004 is http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html

    Set a script to disable non-POSIX usage to ensure portability, add:

    Discussion about Bashisms are at:

    Random

    Rather than using the magic variable $RANDOM, use this, which returns 20816:

    • Indexes in an array within zsh begin with 1 vs. with 0 in bash and sh.

    vzvol is a great example of modular shell code to ensure extensibility and cleanliness of code. It sources functions from files the same way you would import functions and libraries in C.

    Plugins

    Z shell supports plugins and themes.

    There are mutually exclusive alternatives:

    Prezto (at https://github.com/sorin-ionescu/prezto) is a configuration framework for Zsh.

    Antigen is a manager for Zsh plugins (bundles). Antigen lets you switch the prompt theme with a command (for the session) such as:

    Oh My Zsh is the most commonly known.

    Oh My Zsh

    PROTIP: A user community website called “Oh My Zsh” at https://ohmyz.sh (@ohmyzsh) collects third-party plug-ins and themes for the Z shell. As of 2018, their GitHub repository has over 1,300 contributors, 200+ plug-ins, and over 140 themes (of varying quality).

    Use this shell command to install:

    The initial response:

    When prompted with this, type “n”:

    The rest of the response:

    Set .zshrc start-up commands

    Installing oh my zsh results in creation or update of file

    /.zshrc , with suggested settings commented out. Other examples are

    PROTIP: Static values need to be defined to specify PATH, LANG, LC_ALL, PS1, PS2, PS4, etc. shell variables.

    When the operating system starts, it looks for a file with a specific name to execute. Debian-family distros execute .profile , and ignores the .bash_profile that MacOS and RedHat derivatives (CentOS) execute.

    The sh shell and Debian-family distros look for a file named .profile to execute for user login. The bash shell, being generally backwards-compatible with /bin/sh, reads .profile if one exists.

    NOTE: There is a differentiation between interactive login. Each terminal window is a different process and require another password to login.

    PROTIP: Some installers, such as the rvm (Ruby) installer, adds to the .profile file. So edit the .profile file add at the top of the a command to notify that it is being executed. Such as:

    Open the Terminal program.

    This causes an interactive shell to be invoked.

    You are required to provide your password because it logs you in as a user.

    The zsh shell always reads file .zshrc for an interactive shell, whether it’s a login one or not.

    Switch to a text editor to edit in your Home folder file

    This is from here on GitHub. Robby Russell is the original developer of the project.

    mate invokes the TextMate editor.

    Remove the # to activate lines.

    Source aliases for compatibility

    PROTIP: So that you can switch between zsh, bash, sh, put settings that are common among them into a separate file and have each script invoke the file.

    Save the files in GitHub for version control.

    Files in the $HOME folder are backed up.

    Change default shell back to bash

    Switch back the default to Bash:

    Why not Fish?

    Why didn’t Apple go further with alternative FOSS shell Fish (Friendly Interactive SHell)? Information about it:

    Why not jump temporarily to Python?

    There is a rising call for coding Python rather than shell code. Python code is easier to read and maintain, runs a little faster, and can have a proper unit test suite. This article argues the Python is more cross-platform.

    Examples of common OS-level actions:

    • parsing arguments provided when called
    • functions
    • Getting the Time
    • parameters
    • Reading configuration files
    • Downloading Web Pages and Files

    Replace in line — https://stackoverflow.com/questions/10507230/insert-line-at-middle-of-file-with-python

  • Killing (and creating) processes
  • subshells $()
  • Creating (and deleting) directories
  • Running applications
  • Doing date arithmetic
  • Arrays
  • symlinking files
  • Managing files

    Video Tutorials

    https://commandlinepoweruser.com by Wes Bos (@wesbos) present a free yet thorough video course on Zsh.

    Other Resources

    When Jessica Deen (@JLDeen), Microsoft Azure DevOps Evangelist uber-nerd shares her screen at conferences and webinars, people marvel at her terminal configuration. So she shows us how we can set it up at Badass Terminal: WSL, macOS, and Ubuntu dotfiles update. on March 2018 added PowerShell for Windows and support for MacOS. It updates here Badass Terminal: FCU WSL Edition (oh-my-zsh, powerlevel9k, tmux, and more!) that went viral Oct 2017.

    Источник

  • Оцените статью