- Move and copy files in Terminal on Mac
- Move a file or folder locally
- Copy a file or folder locally
- Copy a file or folder remotely
- How to Copy a File Path as Text from Mac Finder in Mac OS X
- Copying File Paths from the Mac Finder
- Related
- Enjoy this tip? Subscribe to our newsletter!
- Thank you!
- Related articles:
- 22 Comments
- 2 Ways to Change the Default Application to Open Files With in Mac OS X
- 1: How to Set the Default Application for a Specific File in Mac OS
- 2: How to Set Default Applications to Open All Files of a Format Type in Mac OS X
- Cmake — собираем переносимые приложения для Mac Os X и Windows
Move and copy files in Terminal on Mac
In Terminal, you can move and copy files locally or remotely using the mv , cp and scp command-line tools.
Tip: It’s easier to move and copy files using the Finder. See Organise files in folders.
Move a file or folder locally
In the Terminal app on your Mac, use the mv command to move files or folders from one location to another on the same computer. The mv command moves the file or folder from its old location and puts it in the new location.
For example, to move a file from your Downloads folder to a Work folder in your Documents folder:
You can also change the name of the file as it’s moved:
Copy a file or folder locally
In the Terminal app on your Mac, use the cp command to make a copy of a file.
For example, to copy a folder named Expenses in your Documents folder to another volume named Data:
The -R flag causes cp to copy the folder and its contents. Note that the folder name does not end with a slash, which would change how cp copies the folder.
Copy a file or folder remotely
In the Terminal app on your Mac, use the scp command to copy a file or folder to or from a remote computer.
scp uses the same underlying protocols as ssh .
For example, to copy a compressed file from your home folder to another user’s home folder on a remote server:
You’re prompted for the user’s password.
The -E flag preserves extended attributes, resource forks and ACL information.
The -r flag, which isn’t used in this example, causes scp to copy a folder and its contents.
Источник
How to Copy a File Path as Text from Mac Finder in Mac OS X
Advanced Mac users who need frequent access to a files complete path in macOS and Mac OS X may find themselves turning to the drag & drop Terminal trick or performing a variety of other tricks to copy an items path, but with Mac OS X 10.11 and later, there’s a new native Copy Pathname option built directly into the Finder. Just as it sounds, it will copy the complete pathname of a file or folder directly to the clipboard.
Copying File Paths from the Mac Finder
Using Copy Item as Pathname in Mac OS X Finder is really easy, here’s all you need to do to copy any items path name directly to the clipboard from anywhere in the file system:
- Navigate to the file or folder you wish to copy the path for
- Right-click (or Control+Click, or a Two-Finger click on trackpads) on the file or folder in the Mac Finder
- While in the right-click menu, hold down the OPTION key to reveal the “Copy (item name) as Pathname” option, it replaces the standard Copy option
- Once selected, the file or folders path is now in the clipboard, ready to be pasted anywhere
The copied pathname is always the complete path, it’s not relative.
As an example, choosing “Copy (file) as Pathname)” in the screen shot example on a file called com.apple.Boot.plist copies in the /Library/Preferences/SystemConfiguration/ folder (where OS X network settings are stored) will copy the following file path into the clipboard, which can then be pasted anywhere as so:
This is demonstrated in the video below:
Though this right-click Copy Pathname option is only available in the latest versions of OS X, there are other ways to copy a file path in all versions of Mac OS X, including with an Automator script, so if you’re not on the latest and greatest you can still get the same feature through the Service menu and the Automator trick..
If you find yourself frequently needing path information on the Mac, two other handy tricks are enabling the Path Bar, which is interactive or showing the complete path in the Finder window titlebars too, which will display the full path to the active folder where ever you are in the Finder within the titlebar.
Related
Enjoy this tip? Subscribe to our newsletter!
Get more of our great Apple tips, tricks, and important news delivered to your inbox with the OSXDaily newsletter.
Thank you!
You have successfully joined our subscriber list.
Related articles:
22 Comments
Awesome find, thank you so much!
Thank You. This was a great find. I needed it. 🙂
This was a handy discovery. I might stress that the option key should be applied after the right-click menu appears. If you apply the option key before, then you get a different menu.
Hello? Is anyone still there after all that time!
I’d got this far using an Automator service but I still couldn’t quite get what I needed. Any ideas anyone?
I use file paths to create local links to files & folders, which I paste into electronic documents.
[I typically create some kind of to-do list and there’ll files all over my computer that I want to locally link to. I’ll put the links in which must have the form:
I can get the path but I need to ‘prepend’ “file://” to it. Then select it, copy it, ⌘K, and embed the local path in the text.
Is there a cool way to do this automatically (Terminal, Automator?). Just in one step?
Thx for the good tip!
great solution and works here.
Hi, much thank for the tutorial. Regarding the mentioned “drag & drop Terminal trick,” I’m pulling my hair out trying to get that to work. I’m admittedly not very familiar with the Terminal, but your post and numerous others indicate that copying a file path from Finder to Terminal is as simple as dragging and dropping. I’m using macOS Sierra 10.12.3, and for the life of me I cannot get that ostensibly simple action to work. No matter what file I try to drag and drop onto the Terminal, the pathname never appears in the Terminal — even when I first hold the file over the Terminal window for a few moments to ensure the Terminal app is in the foreground before then dropping the file on the window. I have even tried clicking option+copy [file] as pathname with a file selected in Finder and then tried all of the several paste options available from the Edit dropdown menu in Terminal, but still nothing does the trick. Am I missing something? Much thanks for any light you can shed.
Fantastic tip – this has been a real pain for me coming from Windows where the current path can be trivially copied/pasted.
However, it only solves the first problem (copying the current path). How can I quickly paste that path in another Finder window to navigate there (in windows it’s paste and enter, and boom, you’re there)?
This is such a common action (especially when developing software) I can’t believe there is not an easy way.
Источник
2 Ways to Change the Default Application to Open Files With in Mac OS X
Each file type has a default application that is associated with it on the Mac. This means that when you double-click a file from the Finder it will open a specific application, for example on a fresh Mac OS installation, all image files (png, jpg, gif, pdf, etc) will default to opening in Preview, and all text documents (txt, rtf, etc) will open in TextEdit.
Over time, the default applications and file associations can change as you install more applications, which sometimes set themselves as the new default app to open a file format with.
If you want to change these default file format associations and have files open in other applications of your choosing, you’ll find there are two simple ways to do this: the first method defines the default application to launch for a specific single file, and the second method will change the application associated with all files of a given format type.
1: How to Set the Default Application for a Specific File in Mac OS
This provides file-specific control over default applications, meaning you can have a document or two that open in one app, while the overall general file type defaults to open in another application. For example, you could set one single PSD file to always open exclusively in Pixelmator, while all other PSD formatted documents continue to open in Adobe Photoshop.
- From the Mac Finder, right-click (or Control+Click) on the file to change the default app for and hold down the OPTION key so that the “Open With” menu becomes “Always Open With”
- Continue to hold OPTION and select the application you want to set as the default for this file
The file will open in the application you selected, and that file will now associate the chosen application as it’s new default to always open within.
By the way, if you’re setting a file type this way and notice duplicate entries in that Open With menu, you can remove those duplicate entries with this quick trick to clean up the Open With contextual menu.
Again, this is specific to the file you chose, and this method will not apply to all files sharing that same file format. If you want to set the default application universally for a file type, that’s what the next tip is for.
2: How to Set Default Applications to Open All Files of a Format Type in Mac OS X
This approach will change the default application universally for all files of a specific format. For example, you could use this to set all files of the type PNG to open within Skitch, all TXT files to open with TextWrangler, and all ZIP files to open with The Unarchiver.
- From the Mac file system, select a file of the general format type you wish to change the default application for
- Pull down the “File” menu and choose “Get Info” (or hit Command+i) to access the Get Info window
- Click the “Open with:” sub menu, then click on the contextual menu and select the new application to associate all files of this format type with
Click the “Change All” button and confirm the change when requested
(Note: if the Change All button is greyed out and unclickable it’s because you have not set an application that is different than the currently set default app. Use the pulldown menu to choose the new application for the Change All button to be usable and to apply the adjustment to all files of the file format type)
This change carries throughout all files of that format used within Mac OS for the active user account, and the filetype-to-application association will stay in place until it has been changed again through the same “Get Info” trick, or until a third party application claims the file format and associates with it directly.
You’ll find this one particularly useful if a newly installed application has assumed control over a file format, like what often happens with Adobe Reader claiming all PDF documents. This ‘Change All‘ trick will allow you to quickly reclaim PDF file types to reopen again in Preview (or your app of choice), which is typically much faster than launching such files in more resource heavy apps like Reader.
The video below demonstrates the latter trick, changing the default application for all files of a given type:
Note these tricks work to set the default application for files in all versions of macOS, Mac OS X, and OS X, including Big Sur, Catalina, Mojave, High Sierra, Sierra, Yosemite, El Capitan, Snow Leopard, Lion, Mountain lion, Tiger, and earlier releases too. Therefore it does not matter which version of Mac system software you are running, you can always changes the default application that opens with a file or file type.
Have any other tips or suggestions for changing application file associations on the Mac? Share in the comments!
Источник
Cmake — собираем переносимые приложения для Mac Os X и Windows
Рано или поздно наступает тот момент, когда приложения из наших лабораторий, полных чудес, вкусных библиотек и красивых фреймворков начинают проситься в большой мир, на компьютеры простых людей, не искушённых в магии. На их компьютерах не то, что не стоят наши новомодные фреймворки и средства разработки, там даже простого компилятора днём с огнем не сыщешь. Не может наше приложение жить без библиотек, которые так редко встречаются в дикой природе, зачахнет оно без них, никогда не видать ему белого света…
Но не всё так печально.
Обычно в таких случаях разработчики создают так называемые бандлы, которые содержат в себе все необходимые библиотеки и плагины для запуска приложения. Чаще всего их создают или при помощи скриптов или зависимых от IDE инструментов или вовсе руками.
Если вы никогда не вылезали за пределы Visual Studio, то вам для счастья особенно многого и не надо, все рецепты создания инсталляторов уже давно известны и обкатаны. Но если вы приверженец кроссплатформенного ПО, то тут начинаются сложности. Зачастую это все приводит к появлению небольшой рощицы из костылей для создания готовых к распространению бандлов без каких-либо намеков на универсальность. Но есть способы этого избежать.
Уже много лет самым популярным способом сборки для кроссплатформенных приложений является cmake, который имеет поддержку кучи платформ и компиляторов, умеет Qt, умеет создавать инсталляторы и dmg’шки и многое другое. Как раз о кроссплатформенном создании бандлов я и хочу рассказать. Для этого в cmake 2.8 появилась прекрасная утилита fixup_bundle
Описание утилиты
Утилита fixup_bundle опрашивает приложение и дополнительный список библиотек(чаще всего плагинов) на предмет наличия внешних зависимостей, после чего она ищет их в списке директорий, который мы заранее приготовили и копирует библиотеки и устанавливает значение RUNPATH, где это необходимо, чтобы приложение и плагины смогли ими воспользоваться. На заключительном этапе утилита проверяет получившийся бандл на наличие внешних зависимостей, если всё плохо, то она сообщает об ошибке.
Подготовка проекта
Проще всего работать с результатом выполнения команды make install. В этом случае, при правильном создании целей установки, получится хорошо структурированный каталог, на который уже будет легко натравливать fixup_bundle.
Ниже приведен мой вариант путей установки для различных типов целей.
if(WIN32)
set(BUNDLE_NAME $<_name>.exe)
set(BINDIR bin)
set(BUNDLE_PATH «$
set(LIBDIR lib$
set(SHAREDIR share)
set(PLUGINSDIR bin)
set(IMPORTSDIR $
set(RLIBDIR $
elseif(APPLE)
set(BUNDLE_NAME $<_name>.app)
set(BUNDLE_PATH «$
set(BINDIR $
set(LIBDIR $
set(RLIBDIR $
set(SHAREDIR $
set(PLUGINSDIR $
set(IMPORTSDIR $
else()
set(BUNDLE_NAME $<_name>)
set(BINDIR bin)
set(BUNDLE_PATH «$
set(LIBDIR lib$
set(RLIBDIR $
set(SHAREDIR share/apps/$<_name>)
set(PLUGINSDIR $
set(IMPORTSDIR $
endif()
Пример использования
install(TARGETS client
RUNTIME DESTINATION $
LIBRARY DESTINATION $
ARCHIVE DESTINATION $
BUNDLE DESTINATION .
)
Аналогичным образом нужно завернуть все устанавливаемые файлы и цели, дабы можно было менять пути для новых платформ простым образом. Это очень облегчает создание бандлов, инкапсулируя все особенности платформ.
Установка плагинов
Все зависимости для библиотек и бинарников будут найдены и прописаны автоматически, при условии, что они есть в путях поиска. Но раз нам удалось собрать приложение, то логично предположить, что все эти пути у нас на руках есть! Сложнее с плагинами и библиотеками, которые подгружаются динамически. Пока не запустишь программу никогда не будешь уверен, что же ей ещё нужно для корректной работы. К сожалению, это не самый лучший вариант. Но мы же разработчики приложения и знаем какие же плагины использует наше пока ещё не вышедшее в свет приложение, поэтому мы можем написать код для их поиска и добавления в цели установки примерно таким образом:
macro(DEPLOY_QT_PLUGIN _path)
get_filename_component(_dir $ <_path>PATH)
get_filename_component(name $ <_path>NAME_WE)
string(TOUPPER $
if($ <_type>STREQUAL «DEBUG»)
set(name «$
endif()
#message($
if(EXISTS $
message(STATUS «Deployng $ <_path>plugin»)
install(FILES $
else()
message(STATUS «Could not deploy $ <_path>plugin»)
endif()
endmacro()
После чего можно будет просто перечислить те Qt плагины, которые реально нужны. И по make install’у они окажутся все в нужном нам месте.
list(APPEND QT_PLUGINS
bearer/qgenericbearer
.
imageformats/qtiff
iconengines/qsvgicon
)
По хорошему, для распространения софта через менеджеры пакетов нужно, чтобы при обычной работе make install’а все внешние библиотеки не трогались, поэтому лучше всего включать режим сборки бандла отдельной опцией в конфигураторе.
option(CREATE_BUNDLE «Create application bundle then install» ON)
Запуск fixup_bundle
Из приведенного куска кода вполне очевидно, как работает fixup_bundle. В конечном итоге для получения бандла достаточно команды make install. А инсталляторы на основе cpack’а уже станут делом техники, но это тема отдельного разговора.
Ну и небольшой пример в виде индикатора прогресса для qml. В приложении используются QtComponents Desktop. Кому интересно, можете попробовать его запустить на Windows или Mac Os X Lion.
Код примера на github’е, там же набор макросов для cmake’а, который делает создание бандлов крайне простым и удобным.
Источник